[Tex/LaTex] “For” loop without “do”; “if” statement without “then”

algorithmicalgorithmicxalgorithms

How can I get rid of the do in a for loop and the then in an if statement when typesetting algorithms using the algorithm and algorithmicx packages?

Best Answer

You can redefine \algorithmicthen and \algorithmicdo:

\renewcommand\algorithmicthen{}
\renewcommand\algorithmicdo{}

Adding the previous lines in the preamble (respectively, before a particular algorithmic environment enclosing the construct inside a group) will remove the "then" and "do" from all the algorithmic environments (for the particular environment, respectively). If the change has to be applied only to some structures of a particular algorithm while others still will have the "then" and "do", then you can define commands to "switch on/off" the expressions:

\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}

\newcommand\NoDo{\renewcommand\algorithmicdo{}}
\newcommand\ReDo{\renewcommand\algorithmicdo{\textbf{do}}}
\newcommand\NoThen{\renewcommand\algorithmicthen{}}
\newcommand\ReThen{\renewcommand\algorithmicthen{\textbf{then}}}

\begin{document}

\begin{algorithm}
\caption{Calculate $y = x^n$}
\label{alg1}
\begin{algorithmic}
\STATE $y \leftarrow 1$
\NoThen
\IF{$n < 0$}
\STATE $X \leftarrow 1 / x$
\ENDIF
\ReThen
\IF{$n > 0$}
\STATE $X \leftarrow 1$
\ENDIF
\NoDo
\FOR{$N \neq 0$}
\STATE $X \leftarrow X \times X$
\ENDFOR
\ReDo
\WHILE{$N \neq 0$}
\STATE $X \leftarrow X \times X$
\ENDWHILE
\end{algorithmic}
\end{algorithm}

\end{document}

enter image description here