The algorithm2e package

Typesets pseudocode in a numbered algorithm float, with commands such as \KwIn, \For, \While, \If and \Return.

Loading the package

\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

The package contains the float and the pseudocode language in one. Control structures take their condition and their body as arguments in braces: \If{condition}{body}, \For{range}{body}. Each statement ends with \;, which prints the semicolon and breaks the line.

Package options set the look. ruled draws rules above and below and puts the caption at the top, vlined marks blocks with a vertical line instead of "end", and linesnumbered numbers the lines.

Main commands

\begin{algorithm}[H] ... \end{algorithm}The float; [H] sets it exactly where it stands in the source.
\KwIn{...}, \KwOut{...}Lines "Input:" and "Output:" at the top; \KwData and \KwResult print "Data:" and "Result:".
\If{condition}{body}Conditional; \eIf{condition}{then}{else} adds an else branch.
\For{$i \gets 1$ \KwTo $n$}{body}For loop.
\While{condition}{body}While loop.
\Return{$m$}Return statement.
\tcp*{comment}Comment at the right end of the line; it also ends the line.
\caption{...}Caption and number "Algorithm 1"; with \label after it you can reference the algorithm.

Complete example

\documentclass{article}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}
\begin{document}
\begin{algorithm}[H]
\caption{Largest element of a list}
\KwIn{list $a_1, \dots, a_n$}
\KwOut{largest element $m$}
$m \gets a_1$\;
\For{$i \gets 2$ \KwTo $n$}{
  \If{$a_i > m$}{
    $m \gets a_i$\tcp*{new maximum}
  }
}
\Return{$m$}\;
\end{algorithm}
\end{document}
Result
The compiled example

Open in the editor

Compiled with pdfLaTeX from TeX Live 2023.

Pitfalls

Related pages