Typesetting algorithms

The framed, numbered “Algorithm 1” pseudocode you see in papers and textbooks is not a built-in LaTeX feature — it comes from packages. The first stumbling block is that several similarly named packages exist. The key is a division of labour: one package supplies the container (a floating, numbered box) and another supplies the contents (the pseudocode itself). This page sorts out that landscape, then covers the classic pairing — the algorithm float wrapping an algpseudocode body — and its self-contained rival, algorithm2e, each with code you can actually compile. Since there is no live renderer here, the prose describes what each one produces.

Two layers: container and contents

Typesetting pseudocode splits into two layers with distinct jobs. The first is the container — a box that floats on the page just like a figure or table, carrying an “Algorithm 1” caption with a running number, cross-references, and even a list of algorithms if you want one. This is provided by the **algorithm** package (\usepackage{algorithm}), which adds a single environment, \begin{algorithm}\end{algorithm}.

The second layer is the contents — commands such as \State (a single line), \While (a loop), and \If (a branch) that set the pseudocode itself, with indentation and line numbers. Here the choices fork: the old **algorithmic package; its more customisable successor algorithmicx (in practice you use the algpseudocode layout built on it); and the separate, independent ecosystem algorithm2e**.

The crucial point: for the body, pick exactly one package. algpseudocode and algorithm2e differ entirely in syntax and philosophy, and mixing them causes clashes. The container algorithm, by contrast, is **meant to be paired with algpseudocode**; algorithm2e brings its own container and body, so it does not need algorithm (and combining them is discouraged). The table below lays out the whole picture.

PackageLayerRole
algorithmContainerFloating box + “Algorithm N” caption/number; pair it with a body package
algorithmicBody (old)The original pseudocode environment; uppercase commands (\STATE …); barely customisable
algpseudocodeBody (modern)The standard algorithmicx layout; looks like algorithmic but far more flexible
algorithm2eBothSelf-contained and independent; its own syntax (\KwIn, \eIf, line-ending \\;); use alone

Note that algorithm ships in the algorithms bundle, which also contains algorithmic. algorithmicx is distributed separately, but loading algpseudocode pulls it in automatically, so you never need to \usepackage algorithmicx yourself.

The algpseudocode commands

You write algpseudocode pseudocode inside the \begin{algorithmic}\end{algorithmic} environment. Note that the environment name differs from the package name (algpseudocode) — the environment is simply algorithmic. The **optional argument [1]** controls line numbering: 0 for none, 1 to number every line, n to number every nth line. Every command is title-cased (\State, \While, …), which is the easiest way to tell it apart from the all-uppercase old algorithmic (\STATE, \WHILE).

The workhorse is \State, which marks the start of each line of pseudocode — you place one \State per statement, such as an assignment or a procedure call. You do not put \State before a block-opening command like \While or \If (those start a new line themselves). The contents of a block are indented automatically, and indentation in your source has no effect on the output. The main commands:

  • \State — the start of one statement (line); used as \State $x \\gets 1$.
  • \For{cond}\EndFor — a for loop; output begins “fordo” and closes with “end for”. \ForAll{cond} exists too.
  • \While{cond}\EndWhile — a while loop; “whiledo” / “end while”.
  • \If{cond}\ElsIf{cond}\Else\EndIf — a branch; “ifthen”, “else ifthen”, “else”, “end if”. \ElsIf and \Else are optional.
  • \Function{name}{args}\EndFunction — a function; “function name(args)” / “end function”. The procedure form \Procedure{name}{args}\EndProcedure has the same shape.
  • \Return — a return value, set as “return …” with an upright (bold) keyword.
  • \Comment{...} — an end-of-line comment, set after a right-pointing triangle ▷.
  • \Require / \Ensure — pre- and post-conditions, each set with a bold “Require:” / “Ensure:” label in front.

These keywords can be replaced. If you prefer the labels to read “Input:” and “Output:” instead of “Require:” and “Ensure:”, redefine them in the preamble: \renewcommand{\algorithmicrequire}{\textbf{Input:}} and \renewcommand{\algorithmicensure}{\textbf{Output:}}. Likewise, rewriting \algorithmicwhile, \algorithmicdo, and friends lets you change the words for loops and branches at will.

A worked example: algorithm + algpseudocode

Combining the two layers looks like this: wrap the outside in an algorithm float, give it a \caption{…} and a \label{…} for referencing, and write the pseudocode in the inner algorithmic environment. Here is the classic algorithm for computing the power y = xⁿ.

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

\begin{algorithm}
  \caption{Calculate $y = x^n$}\label{alg:power}
  \begin{algorithmic}[1]
    \Require $n \geq 0$
    \Ensure $y = x^n$
    \State $y \gets 1$
    \State $X \gets x$
    \State $N \gets n$
    \While{$N \neq 0$}
      \If{$N$ is even}
        \State $X \gets X \times X$
        \State $N \gets N / 2$ \Comment{even case}
      \Else
        \State $y \gets y \times X$
        \State $N \gets N - 1$
      \EndIf
    \EndWhile
    \State \Return $y$
  \end{algorithmic}
\end{algorithm}

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

\end{document}

Compiling this places a box — ruled above and below — floating on the page, with the heading “Algorithm 1 Calculate y = xⁿ” (the number is automatic) across the top. Inside, each line is numbered 1, 2, 3 … down the left edge, and the first two lines show the precondition and result after a bold “Require:” and “Ensure:.” The \While line is set with a bold while and a trailing do, and its body is indented one step. The \Comment note sits at the end of its line after a right-pointing triangle, and the last line reads return followed by y. In the body text, \ref{alg:power} resolves to the box’s number (here 1), so it reads “Algorithm 1 is…”.

Mathematics inside the pseudocode ($N \\neq 0$, $y \\gets 1$) is wrapped in $…$ exactly as in ordinary math mode. \gets is a left arrow (←), the conventional notation for assignment. As always, compile a document that uses algorithm twice so the numbers and cross-references settle.

The rival: algorithm2e

The other major option is **algorithm2e. It is a separate ecosystem that is self-contained in one package** — both container and contents — loaded with \usepackage[...]{algorithm2e} before \begin{document}. Its algorithm environment is itself the float, so there is no inner body environment to nest. Its syntax also differs sharply from algpseudocode.

Two differences stand out. First, input and output use dedicated commands \KwIn{…} and \KwOut{…} (or \KwData{…} and \KwResult{…}), set as a bold “Input:”, “Output:”, “Data:”, or “Result:”. Second, branches and loops take their body as an argument in braces. An if–then–else is written \eIf{cond}{then part}{else part}, passing the block contents in { } (the e means “with else”). \For{cond}{body} and \While{cond}{body} work the same way.

One more rule to watch: **every statement must end with \\;** (a backslash–semicolon). Forget it and the next statement runs onto the same line. Here is a short example.

document.tex
\documentclass{article}
\usepackage[ruled,linesnumbered]{algorithm2e}
\begin{document}

\begin{algorithm}[H]
  \caption{Sum of positive entries}
  \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}

\end{document}

Here the ruled option draws rules above and below with a caption line on top, and linesnumbered numbers each line. The [H] is a placement specifier like a figure’s — it pins the algorithm in place rather than letting it float (h, t, b, p are also available). The box opens with bold “Input:” and “Output:” lines; 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 outputs return s.

A few commands tune the look. \SetAlgoLined (formerly \SetLine) draws vertical lines marking block structure, and \DontPrintSemicolon keeps the line-ending \\; from showing in the output. \KwTo sets “to” and \Return sets “return” as built-in keywords; these too can be redefined — into Japanese, say. Comments go in via \tcc{…} (the /* … */ form) or \tcp{…} (the // form).

Which to use

Both are widely used; this is a matter of idiom, not of one being better. **algorithm + algpseudocode** offers a straightforward, \State-based command set and suits anyone who likes the traditional pseudocode look (keywords at the start of a line, wrapped with do, then, end …) or whose conference template assumes it. **algorithm2e** is popular with those who like explicit input/output declarations, the brace-passed block style and vertical-line layout, and heavy use of multilingual keywords and fine customisation.

To repeat: the rule of thumb is to settle on one body package. Loading both algpseudocode and algorithm2e clashes on shared command names like \For and \If and errors out. Standardise on one across the whole document. And if you use algorithm2e, you do not need the algorithm container — algorithm2e defines its own algorithm environment, so loading both collides on the environment name.