Code Snippet: Algorithms in LaTeX
Setup
Put these two things in your preamble.
We use the algorithm
and algorithmic
packages.
\usepackage{algorithm}
\usepackage{algorithmic}
The following changes the words “Require” to “Input” and “Ensure” to “Output”. This is optional.
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
Usage
\begin{algorithm}[!t]
\begin{algorithmic}[0]
\REQUIRE $K$
\STATE $T = 0$
\FOR{$k = 1:K$}
\STATE $T = T + 1$
\ENDFOR
\ENSURE $T$
\end{algorithmic}
\caption{My algorithm.}
\label{alg:my-algorithm}
\end{algorithm}
Here are the basic commands.
\STATE <text>
\IF{<condition>} \STATE {<text>} \ELSE \STATE{<text>} \ENDIF
\IF{<condition>} \STATE {<text>} \ELSIF{<condition>} \STATE{<text>} \ENDIF
\FOR{<condition>} \STATE {<text>} \ENDFOR
\FOR{<condition> \TO <condition> } \STATE {<text>} \ENDFOR
\FORALL{<condition>} \STATE{<text>} \ENDFOR
\WHILE{<condition>} \STATE{<text>} \ENDWHILE
\REPEAT \STATE{<text>} \UNTIL{<condition>}
\LOOP \STATE{<text>} \ENDLOOP
\REQUIRE <text>
\ENSURE <text>
\RETURN <text>
\PRINT <text>
\COMMENT{<text>}
\AND, \OR, \XOR, \NOT, \TO, \TRUE, \FALSE