The algpseudocode package
Typesets pseudocode in the algorithmic environment with commands such as \State, \If ... \EndIf, \For ... \EndFor and \Function.
Loading the package
\usepackage{algpseudocode}algpseudocode is the pseudocode layout of the algorithmicx bundle. It provides the algorithmic environment, in which every line starts with a command: \State for a statement, \If{...} to open a block and \EndIf to close it. Indentation follows from the blocks.
The numbered float with a caption is not part of it. It comes from the separate package algorithm, so most documents load both.
Main commands
\begin{algorithmic}[1] ... \end{algorithmic} | The pseudocode block; [1] numbers every line, [5] every fifth. |
\State $x \gets 0$ | One statement on a line of its own. |
\If{...} ... \ElsIf{...} ... \Else ... \EndIf | Conditional with optional branches. |
\While{...} ... \EndWhile | While loop; \For{...} ... \EndFor works the same way. |
\Function{Gcd}{$a, b$} ... \EndFunction | Function with name and parameters; \Procedure has the same form. |
\Require, \Ensure | Lines "Require:" and "Ensure:" for input and output conditions. |
\Comment{...} | Comment at the right end of the line. |
\Call{Gcd}{$a, b$} | Call of a function, with the name in small capitals. |
Complete example
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Euclid's algorithm}
\begin{algorithmic}[1]
\Require integers $a \geq b > 0$
\Ensure the greatest common divisor of $a$ and $b$
\Function{Gcd}{$a, b$}
\While{$b \neq 0$} \Comment{until the remainder is zero}
\State $r \gets a \bmod b$
\State $a \gets b$
\State $b \gets r$
\EndWhile
\State \Return $a$
\EndFunction
\end{algorithmic}
\end{algorithm}
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- The commands are written in mixed case (
\State,\EndIf). The older packagealgorithmicuses capitals (\STATE,\ENDIF); copied into analgpseudocodedocument, they give Undefined control sequence. - Do not load
algorithmicandalgpseudocodetogether. The second one stops with "Command \algorithmic already defined". - Without
\usepackage{algorithm},\begin{algorithm}gives Environment align undefined. - The option
noendleaves out the lines "end if", "end while" and "end function". The commands\EndIfand so on stay in the source.
Related pages
- How-to Write pseudocode in LaTeX
- Package
algorithm2e - Error Environment align undefined
- Error Command \vec already defined