Algorithms in LaTeX: algorithm2e, algorithmic and algpseudocode
Quick answer
- Recommended:
\usepackage{algorithm}(the float with a caption) plus\usepackage{algpseudocode}(the pseudocode). - Commands:
\State,\If{}…\EndIf,\For{}…\EndFor,\While{},\Return,\Comment{}. - Line numbers:
\begin{algorithmic}[1]. - Alternative:
algorithm2e, with\;at line ends and braces for blocks. Do not combine it with thealgorithmpackage. - Reference:
\label{alg:name}after\caption, thenAlgorithm~\ref{alg:name}.
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Sum of positive numbers}\label{alg:sum}
\begin{algorithmic}[1]
\State $s \gets 0$
\For{$i \gets 1$ to $n$}
\If{$a_i > 0$}
\State $s \gets s + a_i$
\EndIf
\EndFor
\State \Return $s$
\end{algorithmic}
\end{algorithm}
\end{document}Algorithms in LaTeX are written as pseudocode, set in a numbered float like a figure. Three packages do the work, and they are easy to mix up: the original algorithmic, its successor algpseudocode from the algorithmicx bundle, and the self-contained algorithm2e. This guide compares them, gives a complete example for each, and covers line numbers, captions and references, and the errors that come from loading the wrong combination.
LaTeX Algorithm Packages Compared
algorithm + algpseudocode | algorithm + algorithmic | algorithm2e | |
|---|---|---|---|
| Status | Current, most common | Original, still works | Current, popular |
| Statement | \State | \STATE | text\; |
| If block | \If{c} … \EndIf | \IF{c} … \ENDIF | \If{c}{...} |
| For loop | \For{c} … \EndFor | \FOR{c} … \ENDFOR | \For{c}{...} |
| Procedures | \Procedure, \Function, \Call | No | \SetKwFunction |
| Input / output | \Require, \Ensure | \REQUIRE, \ENSURE | \KwIn, \KwOut |
| Line numbers | \begin{algorithmic}[1] | \begin{algorithmic}[1] | Option linesnumbered |
| Float environment | algorithm (from the algorithm package) | algorithm (same) | Its own algorithm |
The split matters because algorithm and algorithmic are names of environments as well as packages. The algorithm package only provides the floating box with its caption; what goes inside comes from algorithmic or algpseudocode, which both define an environment named algorithmic. algorithm2e provides everything itself.
LaTeX Algorithm with algorithm and algpseudocode
A complete example with inputs, a procedure, a loop, a condition, comments and numbered lines:
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Binary search}\label{alg:bsearch}
\begin{algorithmic}[1]
\Require sorted array $A[1..n]$, target $x$
\Ensure index $i$ with $A[i] = x$, or $0$ if $x$ is absent
\Procedure{BinarySearch}{$A, n, x$}
\State $lo \gets 1$, $hi \gets n$
\While{$lo \le hi$}
\State $mid \gets \lfloor (lo + hi)/2 \rfloor$
\If{$A[mid] = x$}
\State \Return $mid$ \Comment{found}
\ElsIf{$A[mid] < x$}
\State $lo \gets mid + 1$
\Else
\State $hi \gets mid - 1$
\EndIf
\EndWhile
\State \Return $0$ \Comment{not found}
\EndProcedure
\end{algorithmic}
\end{algorithm}
Algorithm~\ref{alg:bsearch} runs in $O(\log n)$ time.
\end{document}The commands you will use most:
| Command | Output |
|---|---|
\State | A statement on its own line |
\If{c}, \ElsIf{c}, \Else, \EndIf | if c then … end if |
\For{c}, \ForAll{c}, \EndFor | for c do … end for |
\While{c}, \EndWhile | while c do … |
\Repeat, \Until{c} | repeat … until c |
\Procedure{Name}{args}, \EndProcedure | procedure NAME(args) |
\Function{Name}{args}, \EndFunction | function NAME(args) |
\Call{Name}{args} | A call, NAME(args) |
\Return | return |
\Comment{text} | ▷ text, aligned right |
\Require, \Ensure | Require:, Ensure: |
Write expressions in math mode ($i \gets i + 1$); \gets prints the assignment arrow ←. To print Input:/Output: instead of Require/Ensure, add \renewcommand{\algorithmicrequire}{\textbf{Input:}} and the same for \algorithmicensure in the preamble.
The Original algorithmic Package
Older papers and some journal templates use algorithmic, with uppercase commands. The structure is the same:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{document}
\begin{algorithm}
\caption{Maximum of a list}\label{alg:max}
\begin{algorithmic}[1]
\REQUIRE list $a_1, \dots, a_n$ with $n \ge 1$
\STATE $m \gets a_1$
\FOR{$i = 2$ \TO $n$}
\IF{$a_i > m$}
\STATE $m \gets a_i$
\ENDIF
\ENDFOR
\RETURN $m$
\end{algorithmic}
\end{algorithm}
\end{document}Do not load algorithmic and algpseudocode together, and do not mix their commands: \STATE works only with the first, \State only with the second.
Algorithms with algorithm2e
algorithm2e is one package that provides both the float and the pseudocode. Blocks take their body in braces, every line ends with \;, and the package options set the look: ruled for rules around the caption, vlined for vertical lines marking blocks, linesnumbered for line numbers.
\documentclass{article}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}
\begin{document}
\begin{algorithm}
\caption{Euclid's algorithm}\label{alg:gcd}
\KwIn{integers $a \ge b \ge 0$}
\KwOut{$\gcd(a, b)$}
\While{$b \neq 0$}{
$r \gets a \bmod b$\;
$a \gets b$\;
$b \gets r$\;
}
\eIf{$a = 1$}{
\tcp{$a$ and $b$ were coprime}
\Return{$1$}\;
}{
\Return{$a$}\;
}
\end{algorithm}
Algorithm~\ref{alg:gcd} terminates because $b$ strictly decreases.
\end{document}The main algorithm2e commands are \If{c}{...}, \eIf{c}{then}{else}, \For{c}{...}, \ForEach{c}{...}, \While{c}{...}, \Repeat{c}{...}, \tcp{comment} and \Return{x}. Custom keywords and function names are declared with \SetKw and \SetKwFunction.
Line Numbers, Captions and References
\begin{algorithmic}[1] numbers every line; [2] numbers every second line. Lines can carry a \label and be referenced like equations, and \listofalgorithms prints a list of all algorithms with their captions:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\floatname{algorithm}{Procedure} % "Algorithm 1" -> "Procedure 1"
\begin{document}
\listofalgorithms
\begin{algorithm}[H] % here, not floating
\caption{Insertion sort}\label{alg:isort}
\begin{algorithmic}[1]
\For{$j \gets 2$ to $n$}
\State $key \gets A[j]$; $i \gets j - 1$
\While{$i > 0$ and $A[i] > key$} \label{line:inner}
\State $A[i+1] \gets A[i]$; $i \gets i - 1$
\EndWhile
\State $A[i+1] \gets key$
\EndFor
\end{algorithmic}
\end{algorithm}
The loop on line~\ref{line:inner} of Procedure~\ref{alg:isort}
shifts larger elements to the right.
\end{document}As with figures, put \label after \caption, and compile twice so references resolve. Algorithms float like figures; the figures guide explains float placement in detail. To rename the list title, use \renewcommand{\listalgorithmname}{List of Procedures}.
Common Errors and Fixes
| Message or symptom | Cause | Fix |
|---|---|---|
| LaTeX Error: Command \algorithmic already defined | algorithmic and algpseudocode are both loaded | Keep one; algpseudocode for \State, algorithmic for \STATE |
| LaTeX Error: Command \algorithm already defined | algorithm and algorithm2e are both loaded | Use algorithm2e alone, or algorithm with algpseudocode |
Undefined control sequence at \State | algpseudocode is not loaded (often algorithmic is loaded instead), or the code is algorithm2e | Load algpseudocode, or use \STATE with algorithmic |
| Package algorithmicx Error: Some blocks are not closed!!! | An \If, \For or \While without its \End... | Add the missing \EndIf, \EndFor or \EndWhile |
| LaTeX Error: Environment algorithm undefined | Only algpseudocode is loaded; it has no float | Add \usepackage{algorithm} |
| Missing $ inserted | Subscripts or symbols such as a_i or \gets outside math mode | Wrap expressions in $...$ |
| The algorithm appears on another page | algorithm is a float | \begin{algorithm}[H], or [htbp] for more freedom |
| algorithm2e lines run together | Missing \; at line ends | End each statement with \; |
A float cannot break across pages, so an algorithm longer than a page sticks out at the bottom. Split it into procedures, or drop the algorithm float and use algorithmic on its own, with a \captionof from the caption package if it still needs a number:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{caption}
\begin{document}
\captionof{algorithm}{A long procedure that may break across pages}
\label{alg:long}
\begin{algorithmic}[1]
\State initialise
\For{$k \gets 1$ to $K$}
\State step $k$
\EndFor
\end{algorithmic}
\end{document}Frequently Asked Questions
How do I write an algorithm in LaTeX?
Load \usepackage{algorithm} and \usepackage{algpseudocode}. Put \begin{algorithm} around the pseudocode with a \caption and \label, and inside it \begin{algorithmic}[1] with one command per line: \State for a statement, \If{...} … \EndIf, \For{...} … \EndFor and \Return. The [1] numbers every line.
Which is better, algorithm2e or algpseudocode?
Both are widely used. algpseudocode (part of algorithmicx) has one command per line, ends each block with \EndIf or \EndFor, and is easy to extend. algorithm2e is a single package with its own algorithm float, braces for blocks, \; at line ends and built-in options for vertical lines and keyword styles. Pick one and do not load both: they define the same commands, such as \If, \For and \Return.
What is the difference between algorithmic and algpseudocode?
algorithmic is the original package from the algorithms bundle and uses uppercase commands such as \STATE, \IF and \ENDIF. algpseudocode, from the algorithmicx bundle, replaces it with mixed-case commands such as \State, \If and \EndIf, and adds \Procedure, \Function and \Call. Both use an environment named algorithmic, so only one of them can be loaded.
How do I add line numbers to an algorithm?
With algorithmic or algpseudocode, give the environment an optional argument: \begin{algorithmic}[1] numbers every line, [5] every fifth. With algorithm2e, add the package option linesnumbered, or \LinesNumbered inside one algorithm. A \label on a line can then be referenced with \ref to print its number.
Why do I get “Undefined control sequence” at \State?
\State is an algpseudocode command. The error means that package is not loaded, usually because the old algorithmic package was loaded instead, which spells it \STATE. Load \usepackage{algpseudocode} (and remove algorithmic), or switch the commands to uppercase. In algorithm2e there is no \State at all; lines end with \; instead.
How do I keep an algorithm from moving to another page?
The algorithm environment is a float, like a figure, so LaTeX places it where it fits. Use \begin{algorithm}[H] to place it exactly where it is in the source; the algorithm package provides [H] itself, and algorithm2e accepts [H] too. Long algorithms that must break across pages can be written without the float, using algorithmic on its own.
Next Steps
- Pseudocode Generator for LaTeX (blog) – Turn a description into algorithm code
- Code Listings – Real source code with listings and minted
- Figures in LaTeX – Float placement, captions and references
- Mathematical Expressions – The math used inside pseudocode
- Theorems & Proofs – Lemmas and proofs for correctness arguments
- Learn LaTeX: Tutorial for Beginners – The basics, from the first document up
Free LaTeX Tools
- LaTeX Preview – Try pseudocode with a live PDF preview
- AI LaTeX Generator – Generate LaTeX from text descriptions
- LaTeX Symbols Reference – Browse math operators and special characters
Write pseudocode faster with AI
Octree's AI editor turns a description or a code snippet into algorithmic pseudocode, fixes package clashes, and compiles your document in seconds.
Try Octree Free →