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 ... \EndIfConditional with optional branches.
\While{...} ... \EndWhileWhile loop; \For{...} ... \EndFor works the same way.
\Function{Gcd}{$a, b$} ... \EndFunctionFunction with name and parameters; \Procedure has the same form.
\Require, \EnsureLines "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}
Result
The compiled example

Open in the editor

Compiled with pdfLaTeX from TeX Live 2023.

Pitfalls

Related pages