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.

Not sure it worked on your document? Paste it into LetX and compile it, free and in the browser.

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".

Related LaTeX fixes

Browse all LaTeX problems & fixes, or start with the LaTeX guide.

Learn the topic properly

Try the fix in LetX

Open the editor, paste your code, and compile in seconds to see the error clear. Free, in your browser.

Open LetX Free