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}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- Do not load
algorithm2etogether with the packagesalgorithm,algorithmicoralgpseudocode.algorithmandalgorithm2eboth define the environmentalgorithm, and the second one stops with "Command \algorithm already defined". - A statement without
\;at its end runs into the next statement on the same line. - With the option
ruled, the caption is printed at the top of the algorithm wherever\captionstands in the source. [H]is built into the package and does not need thefloatpackage.
Related pages
- How-to Write pseudocode in LaTeX
- Package
algpseudocode - Error Command \vec already defined
- How-to Insert source code in LaTeX