How-to

How to Write Algorithms and Pseudocode in LaTeX

The fix

Two common choices: algorithm2e (self-contained) or the algorithm + algpseudocode pair from algorithmicx. Both produce a numbered, captioned "Algorithm" float with \State, \For, \While, and \If keywords and automatic indentation. Pick one — do not mix them in a single document.

Example

\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{algorithm}
\caption{Binary search}
\begin{algorithmic}[1]
\State $lo \gets 0$
\While{$lo \le hi$}
  \State $mid \gets (lo+hi)/2$
\EndWhile
\end{algorithmic}
\end{algorithm}

Frequently asked questions

Which algorithm package should I use?

algorithm2e is popular and self-contained; algorithmicx (algorithm + algpseudocode) integrates cleanly with the algorithm float. Do not load both — pick one.

How do I reference an algorithm?

Add \label{alg:key} after the \caption and cite it with \ref{alg:key}, or with cleveref use \cref{alg:key} for "Algorithm 1".

Try the fix in LetX

Open the editor, paste your code, and compile in 1 second to see the error clear — free, in your browser.

Open LetX Free