Type “latex algorithm package” into a search box and four almost identical names come back — algorithm, algorithmic, algorithmicx, algorithm2e — and there is a fair chance the preamble you are debugging right now loads two of them that refuse to sit in the same document. That tangle is the real subject of this page, because once it is untangled, typesetting pseudocode in LaTeX is easy. The thing to hold on to is that pseudocode is not a code dump: unlike the source listings on the sibling page, an algorithm is set like mathematics — italic variables, an arrow for assignment, bold keywords — inside a numbered float you can point at with \ref. Below: which pair of packages to actually load, the exact errors the wrong pair produces, and both dialects written out in full.
Pseudocode vs listings: pasted code, or typeset prose
In one sentence: listings preserves characters, pseudocode typesets meaning. What you hand to listings or minted is treated verbatim — every space and symbol survives to the page — which is exactly what real source code needs, and that trade-off belongs to the sibling page. Pseudocode inverts it. Write $y \gets 1$ and y is set as an italic variable while \gets becomes the arrow ←: the body lives in math mode, not in a verbatim environment. Only the keywords stand up in bold roman, visually separated from the variables. That contract — italic for variables, bold for keywords — is the textbook convention that runs back through Knuth’s The Art of Computer Programming. The name \gets is itself a piece of that heritage: it comes from computer science, from reading x \gets 1 as “x gets 1”.
The second difference is where the thing sits. An lstlisting stays put in the flow of the text, whereas pseudocode conventionally goes inside a float, exactly like figure or table. LaTeX then moves it clear of an awkward page break, gives it a numbered “Algorithm 1” heading, and lists it in \listofalgorithms. Grasp the one structural fact that the container (the float) and the contents (the pseudocode) come from different packages, and the four confusing names fall into place at once.
Which package do you actually \usepackage?
If you are starting fresh, the answer is two lines long. Either put \usepackage{algorithm} next to \usepackage{algpseudocode}, or load \usepackage{algorithm2e} on its own. Almost any other combination ends badly. The reason it is confusing is that the CTAN package names and the style-file names do not line up. algorithm.sty does not come from a package called algorithm; it comes from the algorithms bundle — plural. And algpseudocode.sty comes from algorithmicx. So you type two file names in your preamble while actually installing two bundles with entirely different names.
| Bundle | Style files it installs | Role |
|---|---|---|
algorithms | algorithm.sty, algorithmic.sty | The container (the algorithm float) plus the original body, algorithmic, whose all-caps commands (\STATE) date back to 1994 and are now superseded |
algorithmicx | algorithmicx.sty, algpseudocode.sty, algcompatible.sty | Body only. János Szász’s 2005 rewrite, with algpseudocode as its standard layout. It ships no container at all |
algorithm2e | algorithm2e.sty | A self-contained world supplying both container and contents. Maintained by Christophe Fiorio since 1996. Never load it alongside algorithm |
% Camp 1 -- two packages, two jobs. This is the usual choice.
\usepackage{algorithm} % the float: \begin{algorithm}, \caption, \listofalgorithms
\usepackage{algpseudocode} % the body: \begin{algorithmic}, \State, \If, \For
% Camp 2 -- one package does everything. Do NOT also load algorithm.
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}Just how strict that division of labour is becomes obvious when you open algorithm.sty: under a hundred lines, and not one of them says anything about pseudocode. All it does is load the float package, declare one new float type with \newfloat{algorithm}{htbp}{loa}, name it “Algorithm”, and define \listofalgorithms — that is the whole package (the copy in TeX Live 2024 is v0.1, dated 24 August 2009). A pleasing side effect: it treats any option it does not recognise as the name of the float. Write \usepackage[Procedure]{algorithm} and every caption in the document reads “Procedure 1”, “Procedure 2”.
When you get Command \algorithm already defined.
That error means exactly one thing: you are loading both algorithm and algorithm2e. Each of them wants to create an environment called algorithm, so whichever arrives second runs into the first. Delete one of the two from your preamble and it is fixed. For the same reason the wording changes with the load order: put algorithm2e first and algorithm second, and you get ! LaTeX Error: Command \listofalgorithms already defined. instead — same cause. The other common one is ! LaTeX Error: Command \algorithmic already defined., which is what you see when the old algorithmic and the newer algpseudocode are loaded together. The algorithmicx family is the successor to algorithmic; you never need both.
% Each of these three preambles stops the compile.
\usepackage{algorithm}\usepackage{algorithm2e}
% ! LaTeX Error: Command \algorithm already defined.
\usepackage{algorithm2e}\usepackage{algorithm}
% ! LaTeX Error: Command \listofalgorithms already defined.
\usepackage{algorithmic}\usepackage{algpseudocode}
% ! LaTeX Error: Command \algorithmic already defined.
% If a class or a co-author really forces algorithm2e into a document that
% already owns the algorithm float, this option renames the environment to
% algorithm2e and \listofalgorithms to \listofalgorithmes, so nothing collides.
\usepackage[algo2e]{algorithm2e}The nastiest combination, though, throws no error at all. Load algorithm2e and algpseudocode side by side and the document compiles without a murmur. That is because when algorithmicx defines a user-facing name such as \For or \If, it first checks whether that name already exists and, if it does, silently declines to define it. The algorithm2e meanings therefore survive, and nothing goes wrong until you write an algorithmic body — at which point something apparently unrelated, like ! Missing number, treated as zero., erupts on the \EndWhile line. Breaking as far as possible from the cause is arguably worse than a clean error. algorithm2e carries its algo2e option precisely to defuse collisions like this, and when you use it \listofalgorithms becomes the differently spelled \listofalgorithmes — a trace of the package’s French-speaking home.
\begin{algorithm} is a float: \caption, \label, [H]
algorithm is a genuine float in exactly the sense figure and table are. Its default placement is htbp — here, top, bottom, then a page of its own — and its list file has the extension .loa. Everything you know from figures therefore carries over: \caption{…} makes the numbered “Algorithm 1” heading, and a \label{alg:…} placed immediately after it lets the text pull the number with \ref{alg:power} and the page with \pageref{alg:power}. Put the \label before the \caption and the number comes out wrong — off by one, or the section number — so keep the order. Write \listofalgorithms near the top of the document — the sibling of \listoffigures and \listoftables — and you get a “List of Algorithms” pairing each number with its caption text. As always, the numbers, references and list only settle after two compilation runs. And when floating is exactly what you do not want, \begin{algorithm}[H] pins the box where you wrote it — [H] works out of the box because algorithm already loads the float package.
Writing the body: \State, \If, \For, \While, \Function
The inner environment is called algorithmic — the last trap in the naming: the package is algpseudocode but the environment is not. Every command is title-cased: \State opens one statement line, and blocks close explicitly with \If … \EndIf, \For … \EndFor and so on. The optional argument at the start sets the line-numbering interval: [1] numbers every line, [5] every fifth, and omitting it numbers none. The example below is a binary search, and it exercises branches, a loop, a function, a precondition and an end-of-line comment.
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\listofalgorithms
\begin{algorithm}
\caption{Binary search}\label{alg:bsearch}
\begin{algorithmic}[1]
\Require sorted array $a[1..n]$, key $k$
\Ensure index of $k$, or $0$
\Function{Search}{$a,k$}
\State $lo \gets 1$;\ $hi \gets n$ \label{ln:init}
\While{$lo \le hi$}
\State $m \gets \lfloor (lo+hi)/2 \rfloor$ \Comment{midpoint}
\If{$a[m] = k$}
\State \Return $m$
\ElsIf{$a[m] < k$}
\State $lo \gets m+1$
\Else
\State $hi \gets m-1$
\EndIf
\EndWhile
\State \Return $0$
\EndFunction
\end{algorithmic}
\end{algorithm}
Algorithm~\ref{alg:bsearch} halves the interval; the bounds are set on
line~\ref{ln:init}, page~\pageref{alg:bsearch}.
\end{document}Here is what comes out. A box ruled above and below floats onto the page, headed “Algorithm 1 Binary search”. Inside, \Require and \Ensure produce the bold labels Require: and Ensure:, set outside the numbering. The numbers start at the \Function line and run 1, 2, 3 … down the left edge, and \Comment{midpoint} sets a small triangle at the end of the line: ▷ midpoint. The name in \Function{Search}{$a,k$} is set in small capitals, and to invoke it from another line you write \Call{Search}{$a,k$}. Since plenty of people want different labels: the strings Require: and Ensure: live in \algorithmicrequire and \algorithmicensure, so \renewcommand{\algorithmicrequire}{\textbf{Input:}} turns the first one into Input:.
| Command | What it sets | Notes |
|---|---|---|
\State | one numbered line | One per statement; omit it and the text joins the previous line |
\Require / \Ensure | Require: / Ensure: | Pre- and postconditions, set outside the line numbering |
\If ... \ElsIf ... \Else ... \EndIf | if … then / else if / else / end if | The command is spelled \ElsIf — one “e” short of “else”, and a frequent typo |
\For ... \EndFor | for … do … end for | \ForAll{…} gives for all …; the condition goes in braces |
\While ... \EndWhile | while … do … end while | \Repeat … \Until{…} is available in the same shape |
\Function ... \EndFunction | function Name(args) … end function | The name is set in small caps; call it with \Call{Name}{args}. \Procedure is the sibling |
\Return | return | Combine it with \State, as in \State \Return $y$ |
\Comment | ▷ comment text | Goes at the end of a line; the triangle lives in \algorithmiccomment |
The most common accident in this camp is forgetting a \State, and it produces no error. Follow \State $x \gets 1$ with a bare $y \gets 2$ and the output reads “1: x ← 1 y ← 2” — two statements crammed onto one line, and the numbering one short. If the line count looks wrong, suspect this first. And if you meet all-caps commands like \STATE, \WHILE, \ENDWHILE in an old conference template, that is the 1994-vintage algorithmic dialect. To reuse such a manuscript unchanged, load \usepackage{algcompatible} instead of algpseudocode: the uppercase commands keep working, on top of the algorithmicx engine.
Numbering the lines, and citing “line 3”
Line numbers are referenceable. Open the algorithmic environment with [1], put \label{ln:init} at the end of the line you want to cite, and \ref{ln:init} in the text expands to that line’s number. In the example above the \Function line is 1, so \ref{ln:init} comes out as 2. This matters more than it sounds: write “the test on line 3” by hand and adding one statement later turns your prose into a lie. The same idiom works in algorithm2e — enable linesnumbered and put \label{…} after the \; that ends the line. One caveat: labelling an unnumbered line is meaningless, because without [1] or linesnumbered there is no number to point at.
algorithm2e: braces instead of \End…, and the \; you must not forget
The other camp does not close a block with a command like \EndFor. It passes the body as a brace argument — \For{condition}{body}, \While{condition}{body}, and for if–then–else \eIf{cond}{then}{else} (\uIf when there is no else, \lIf to keep it on one line). Input and output get dedicated commands, \KwIn{…} and \KwOut{…}, set as bold Input: and Output: (use \KwData{…} and \KwResult{…} if you prefer the words Data: and Result:). The great pitfall is that every statement must end with \;. Forget it and there is no error — the next statement simply runs onto the same line. If you would rather not see the “;” in print, \DontPrintSemicolon hides it (the \; itself is still required). The whole look is chosen at load time: ruled (rules above and below), boxed (a box around everything), vlined and lined (two ways of drawing vertical block lines), plain (the default), plus linesnumbered for line numbers. Those three line options are literally the in-document commands \SetAlgoVlined, \SetAlgoLined and \SetAlgoNoLine applied for you. TeX Live 2024 ships v5.2, dated 18 July 2017.
\documentclass{article}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}
\begin{document}
\listofalgorithms
\begin{algorithm}
\DontPrintSemicolon
\KwIn{an array $a[1..n]$}
\KwOut{the sum $s$ of its positive entries}
$s \gets 0$\;\label{ln:zero}
\For{$i \gets 1$ \KwTo $n$}{
\eIf{$a[i] > 0$}{
$s \gets s + a[i]$\;
}{
\tcp{negative or zero: skip}
}
}
\Return $s$\;
\caption{Sum of positive entries}\label{alg:sum}
\end{algorithm}
Algorithm~\ref{alg:sum} accumulates into $s$, initialised on line~\ref{ln:zero}.
\end{document}The heading comes out as “Algorithm 1: Sum of positive entries” — the colon after the number is the visible difference from the algorithm float. Above the body sit Input: and Output:; the body reads for i ← 1 to n do and if … then … else, with a vertical rule down the left of each block because we asked for vlined. \tcp{…} is an inline comment and prints as // negative or zero: skip. Note that \caption is written at the end of the environment — that is the algorithm2e convention, and with ruled the heading still appears at the top of the box. The same text goes into \listofalgorithms. And since the algorithm2e environment is a float by default too, \begin{algorithm}[H] is available when you need it to stay put.
Keywords in French or German: the onelanguage option
algorithm2e can translate the keywords of the pseudocode itself. Only this camp offers it; algpseudocode has no equivalent. The options are french, german, ngerman, spanish, italiano, portuguese, czech, slovak, croatian and english. There is a step in the behaviour, though. \usepackage[french]{algorithm2e} on its own renames the float to “Algorithme 1 :” but leaves \For and \eIf printing in English — to get French you use the French command names, \Pour{…}{…}, \Si{…}{…}, \KwA. If you would rather not rewrite the command names in an existing manuscript, add onelanguage: with \usepackage[french,onelanguage]{algorithm2e}, the very same \For and \eIf come out as pour i ← 1 à n faire and si … alors … sinon … fin. For German, [german,onelanguage] gives für i ← 1 bis n tue, wenn … dann … sonst … Ende, under the heading “Algorithmus 1:”.
% Keep the English command names, print French keywords.
\usepackage[french,onelanguage,ruled,linesnumbered]{algorithm2e}
% \For{...}{...} -> pour i <- 1 a n faire ... fin
% Without onelanguage, only the float name is translated; use the
% French command names for a French body.
\usepackage[french,ruled]{algorithm2e}
% \Pour{...}{...}, \Si{...}{...}, \KwASo which one should you use: algpseudocode or algorithm2e
If the template you are submitting to names one of them, use that — many conference classes tune their margins and fonts around a specific choice. Otherwise: algpseudocode if you want the pseudocode to read as mathematical prose, and algorithm2e if you want explicit input/output declarations, block rules, or translated keywords. The table settles the rest.
| Aspect | algorithm + algpseudocode | algorithm2e |
|---|---|---|
packages | Two, one for the float and one for the body | One, self-contained |
block syntax | Explicit closers: \If{…} … \EndIf | Body as brace arguments: \eIf{…}{…}{…} |
input / output | \Require / \Ensure — pre- and postconditions | \KwIn / \KwOut — explicit input and output |
end of line | Nothing needed; \State opens the line | \; is mandatory — omit it and the next statement joins the line |
line numbers | The optional argument of \begin{algorithmic}[1] sets the interval | The linesnumbered option (and rightnl to move them right) |
keyword language | English only; you redefine \algorithmicwhile and friends one by one | Options such as french and german; with onelanguage the command names stay English |
Whichever you pick, the presentation layer is identical: \caption gives the numbered heading, \label and \ref let the text point at it, \listofalgorithms builds the list, and two compilation runs settle the numbers. And once more, because it is the whole lesson of this page: use exactly one body package per document. With algorithm2e, never load algorithm. With algpseudocode, never load algorithmic. That one line of discipline prevents nearly every accident involving the four confusable names we started with. If what you actually want is real source code with syntax colouring and line numbers rather than pseudocode, the sibling page on listings and minted is your destination.