Algorithms (algorithm2e/algpseudocode)

There is more than one way to put code on the page. verbatim reproduces what you typed; listings and minted show real source with colour and line numbers; and a third way shows a language-independent procedure in a numbered “Algorithm 1” box — pseudocode. Unlike real code, pseudocode is set as a *float*: it drifts on the page like a figure or table and carries a caption, a running number, cross-references, and a list of algorithms. This page focuses on presenting that pseudocode well as a *listed object* — captions and numbering above all. The full, command-by-command treatment of the same packages lives at **/learn/math/algorithms**; here we give the map of the two ecosystems and a minimal worked example of each.

Pseudocode is set as a float

Where verbatim and listings place code in the flow of the text, pseudocode is normally presented inside a float. A float is a box — like figure or table — that LaTeX positions automatically, steering it clear of awkward page breaks. That buys two things. First, a numbered “Algorithm 1” caption that you can point at from the text with \ref. Second, a long algorithm is not split clumsily across a page boundary — the inner body environment can break across pages if placed inline, but the float box stays whole and moves to the next page as a unit.

The first stumbling block is that several similarly named packages exist. The key is a division of labour — one package supplies the container (a numbered floating box) and another supplies the contents (the pseudocode itself) — but that split applies to only one of the two camps. In practice there are two broad choices.

  • **Two layers — algorithm (container) + algpseudocode (contents).** The algorithm float provides the floating box, caption, and number; algpseudocode (the standard algorithmicx layout) provides the pseudocode body — \State, \For, \If, and friends.
  • **One package — algorithm2e.** Self-contained: it brings its own float, caption, and body commands (\KwIn/\KwOut, \eIf, …). You do not add algorithm (loading both clashes on the float environment name).

The most important rule, stated up front: settle on one camp for the whole document. algpseudocode and algorithm2e differ entirely in syntax and philosophy, and loading both clashes on shared command names such as \For and \If. Whichever you choose, compile the document twice as usual so the numbers, cross-references, and list of algorithms settle.

Captions, numbers, references, and the list of algorithms

Presentation is this page’s focus. In either camp, \caption{…} produces an “Algorithm N” heading, with N numbered automatically in order of appearance. Put \label{key} right after it and the body text can pull that number with \ref{key} (or the page with \pageref{key}) — exactly as you reference a figure or table.

A second benefit of a numbered float is the list of algorithms. Alongside \listoffigures and \listoftables, writing **\listofalgorithms** generates a contents-like list collecting each algorithm’s number and caption. What appears there is the text you gave to \caption, and it works the same under the algorithm float and under algorithm2e. Note that algorithm2e also offers a separate title-only macro distinct from \caption; that one does not add an entry to the list of algorithms.

Where the caption goes differs by convention. Under the algorithm float you may place \caption either before or after the body, just like a figure (most people put it on top). Under algorithm2e, the convention is to put \caption at the end of the environment, and that caption doubles as the reference name in the list of algorithms.

Camp 1: algorithm + algpseudocode

Wrap the outside in an algorithm float and write the pseudocode in the inner algorithmic environment (the package is algpseudocode, but the environment is named algorithmic). Every body command is title-cased (\State, \While, …), which is how you tell it from the all-uppercase old algorithmic (\STATE). The commands you reach for most:

  • \State — the start of one statement (line); one per statement.
  • \For{…}\EndFor / \While{…}\EndWhile — loops.
  • \If{…}\ElsIf{…}\Else\EndIf — branches.
  • \Function{name}{args}\EndFunction, plus \Return — functions and return values.
  • \Require / \Ensure — pre- and post-conditions (with a bold label).
  • \Comment{…} — an end-of-line comment.

The optional argument [1] controls line numbering: 1 numbers every line, n every nth line, and omitting it gives none. Here is a minimal example computing the power y = xⁿ — note the \label placed right after \caption.

document.tex
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}

\listofalgorithms

\begin{algorithm}
  \caption{Calculate $y = x^n$}\label{alg:power}
  \begin{algorithmic}[1]
    \Require $n \geq 0$
    \State $y \gets 1$
    \While{$n \neq 0$}
      \State $y \gets y \times x$
      \State $n \gets n - 1$ \Comment{count down}
    \EndWhile
    \State \Return $y$
  \end{algorithmic}
\end{algorithm}

アルゴリズム~\ref{alg:power} は累乗を計算する。

\end{document}

Compiling places a box — ruled above and below — floating on the page, headed “Algorithm 1 Calculate y = xⁿ” (the number is automatic). Each line is numbered 1, 2, 3 … down the left edge, and \ref{alg:power} in the body resolves to that number (here 1). The \listofalgorithms at the top yields an entry like “1 Calculate y = xⁿ … page.” For the output of each command — including \ElsIf and \Function — see **/learn/math/algorithms**.

Camp 2: algorithm2e

algorithm2e is a separate ecosystem, self-contained in one package (current release 5.2, 2017). Load it with \usepackage[…]{algorithm2e} before \begin{document}; its algorithm environment is itself the float. You pick the look with load-time options — ruled (rules top and bottom), boxed (a box around the whole), vlined/lined (vertical lines marking blocks), plain (the default, undecorated) — and linesnumbered adds line numbers. Three syntax points matter:

  • Input/output use dedicated commands \KwIn{…}/\KwOut{…} (or \KwData{…}/\KwResult{…}), set as a bold “Input:”, “Output:”, and so on.
  • Branches and loops take their body as a brace argument. An if–then–else is \eIf{cond}{then}{else}; loops are \For{…}{body} and \While{…}{body} (with \KwTo for “to”).
  • **Every statement ends with \\;** (backslash–semicolon). Forget it and the next statement runs onto the same line. To hide the “;” in the output, use \DontPrintSemicolon.
document.tex
\documentclass{article}
\usepackage[ruled,linesnumbered]{algorithm2e}
\begin{document}

\listofalgorithms

\begin{algorithm}
  \caption{Sum of positive entries}\label{alg:sum}
  \KwIn{an array $a[1..n]$}
  \KwOut{the sum $s$ of its positive entries}
  $s \gets 0$\;
  \For{$i \gets 1$ \KwTo $n$}{
    \eIf{$a[i] > 0$}{
      $s \gets s + a[i]$\;
    }{
      skip\;
    }
  }
  \Return $s$\;
\end{algorithm}

アルゴリズム~\ref{alg:sum} は正の要素を合計する。

\end{document}

The ruled option draws rules top and bottom with a caption line on top, and linesnumbered numbers each line. The box opens with bold “Input:” and “Output:”; the \For line reads for i ← 1 to n do with its body indented; and \eIf sets the ifthen true-block above the else false-block. A line break happens at each \;, and the final line reads return s. The \caption text appears verbatim in \listofalgorithms. For finer control — [H] to pin it in place rather than float, \SetAlgoLined to draw vertical block lines, and the rest — see **/learn/math/algorithms**.

Which to use

Both are widely used; this is a matter of idiom, not of one being better. Use the quick guide below to narrow it down.

Aspectalgorithm + algpseudocodealgorithm2e
構成Two layers, two packagesOne self-contained package
本体の書き方Plain \State-led commandsBlock body passed in braces
入出力\Require / \Ensure\KwIn / \KwOut (explicit)
行末Not required\\; required
向く人Traditional look; templates that assume itExplicit I/O, vertical lines, multilingual keywords

Either way, the presentation is the same: \caption gives a numbered heading, \label/\ref reference it, and \listofalgorithms builds the list. To repeat: settle on one body package — and if you use algorithm2e, do not load the algorithm container. The exhaustive command reference and longer worked examples live at **/learn/math/algorithms**. If instead you want real source code with colour and line numbers (actual code, not pseudocode), reach for listings/minted on **/learn/code-verbatim/code-listings**.