Written and maintained by CASRAI Editorial Board
Last updated
Typesetting a LaTeX algorithm allows researchers, computer scientists, and quantitative analysts to present computational procedures, mathematical routines, and data processing workflows with mathematical precision. In scientific publishing, standardizing algorithmic notation ensures that peer reviewers and readers can inspect logic, verify preconditions, and trace state transitions without deciphering language-specific implementation quirks.
What it is used for in research
In peer-reviewed research across computer science, operations research, statistics, bioinformatics, and computational physics, presenting computational methods requires a standardized, language-agnostic representation known as pseudocode. Implementing an algorithm in LaTeX serves several distinct functions in scholarly manuscripts:
- Formal Specification: Communicates procedural steps, recurrence relations, and control flow without tying the methodology to specific programming languages such as Python, C++, or MATLAB.
- Mathematical Rigor: Seamlessly combines mathematical notation—including subscripts, summations, set notation, and Greek symbols (such as α, β, and θ)—directly within conditional statements and variable assignments.
- Floating Layout and Referencing: Integrates with LaTeX float management, allowing algorithms to float like figures or tables, receive automatic numbering, generate entries in a List of Algorithms, and support precise cross-referencing across the text.
- Journal Compliance: Meets camera-ready formatting guidelines mandated by publishers such as IEEE, ACM, Springer, Elsevier, and SIAM. Many academic conferences require pseudocode formatted via standard packages for reproducible methodology sections.
Researchers writing computational papers often pair their algorithmic descriptions with formal theorem environments using LaTeX theorem environments to establish convergence bounds and proof techniques, and link their equations using LaTeX equation labels and cross-referencing.
Install or access (official source only)
Modern TeX distributions—including TeX Live, MacTeX, and MiKTeX—include standard algorithm packages by default. Researchers working in browser-based collaborative environments like web-based LaTeX editors such as Overleaf have these packages pre-installed without requiring manual downloads.
To verify or install packages manually on local systems via package managers:
- TeX Live / MacTeX (tlmgr): Run
tlmgr install algorithmicx algorithms algorithm2efrom your terminal. - MiKTeX: Open the MiKTeX Console, navigate to Packages, search for
algorithmicx,algorithms, oralgorithm2e, and click Install. - Comprehensive TeX Archive Network (CTAN): Official distributions are archived and maintained on CTAN at ctan.org/pkg/algorithmicx, ctan.org/pkg/algorithms, and ctan.org/pkg/algorithm2e.
There are two primary package ecosystems for typesetting algorithms in LaTeX. Authors should select one ecosystem per manuscript to prevent macro collisions:
- The algorithmicx suite (recommended): Combines the floating wrapper package
algorithmwith the modern syntax packagealgpseudocode. - The algorithm2e package: An all-in-one environment that manages both the floating box and the pseudocode syntax with built-in line connectors.
Step-by-step task (numbered, with menu names or commands exactly as in the current docs)
The following step-by-step workflow demonstrates how to structure, format, and typeset an algorithm using the standard algorithm and algpseudocode suite.
Step 1: Declare packages in the manuscript preamble
Add the floating container package (algorithm) and the algorithmic syntax engine (algpseudocode) to your document preamble before begin{document}:
documentclass{article}
usepackage{amsmath}
usepackage{algorithm}
usepackage{algpseudocode}
Step 2: Initialize the algorithm float and numbering
Wrap the procedure inside an algorithm float environment. Set optional float placement parameters (such as [t] for top of page or [h] for here) and open the algorithmic environment. Pass [1] to begin{algorithmic} to enable line numbering on every line:
begin{algorithm}[t]
caption{Euclidean Algorithm for Greatest Common Divisor}
label{alg:euclid}
begin{algorithmic}[1]
Important: Always place the label{alg:...} command immediately after the caption{...} command. Placing the label outside or before the caption causes LaTeX to assign the enclosing section number rather than the algorithm index.
Step 3: Define inputs, outputs, and preconditions
Use Require to declare input data, assumptions, or prerequisites, and Ensure to state output variables, postconditions, or returned results:
Require Integers $a, b$ where $a ge b ge 0$
Ensure $g = gcd(a, b)$
Step 4: Draft procedural steps and control structures
Each execution line inside algorithmic must begin with State. For unnumbered explanatory notes, use Statex. Nest conditionals and loops using matched control blocks:
State $r gets a bmod b$
While{$r neq 0$}
State $a gets b$
State $b gets r$
State $r gets a bmod b$
EndWhile
State Return $b$
Step 5: Close environments and cross-reference in text
Close the environments in reverse order and reference the algorithm in your manuscript body using a non-breaking space (~):
end{algorithmic}
end{algorithm}
The procedure in Algorithm~ref{alg:euclid} terminates in logarithmic time.
Alternative: Standalone implementation with algorithm2e
If your target journal specifies algorithm2e, use its all-in-one syntax with explicit semicolon line terminators (;):
usepackage[ruled,vlined,linesnumbered]{algorithm2e}
begin{algorithm}[t]
caption{Factorial Calculation}
label{alg:factorial}
KwData{Positive integer $n$}
KwResult{Factorial value $f = n!$}
$f gets 1$;
For{$i gets 1$ KwTo $n$}{
$f gets f times i$;
}
KwRet{$f$};
end{algorithm}
Output and how to read it
When compiled with pdfLaTeX, XeLaTeX, or LuaLaTeX, the code generates a structured, floating presentation block containing five distinct components:
- Border and Header Rules: A ruled style displays a prominent top horizontal line, a separating rule beneath the caption title, and a closing bottom rule terminating the block.
- Numbered Caption: Displays a standardized label (e.g., Algorithm 1: Euclidean Algorithm for Greatest Common Divisor) that increments automatically and syncs with the document’s cross-referencing table.
- Precondition Block: Prominently renders bold keywords such as Require: (or Input:) and Ensure: (or Output:) flush with the left margin.
- Line Numbers: Displayed in small font along the left gutter (1, 2, 3…), allowing peer reviewers and co-authors to reference specific statements in methodological critiques.
- Nested Indentation: Loop bodies (inside
whileorfor) and conditional blocks (insideif,else if, andelse) indent by standard margins, visually communicating execution hierarchy without ambiguity.
When researchers archive computational preprints on platforms like TechRxiv vs arXiv, clearly delineated pseudocode ensures that independent research teams can reimplement models in other software languages, supporting scientific reproducibility. Documenting algorithms alongside standardized metadata frameworks such as CodeMeta further enhances citation tracking and software asset governance.
Troubleshooting
Typesetting algorithms frequently triggers specific compiler diagnostics. The table below identifies the most common issues and their direct solutions:
| Error / Symptom | Root Cause | Corrective Action |
|---|---|---|
LaTeX Error: Command algorithmic already defined |
Loading mutually incompatible packages simultaneously (e.g., loading both algorithm2e and algpseudocode/algorithmic). |
Choose one package family. Remove conflicting usepackage statements from your preamble. |
Undefined control sequence State |
Declaring usepackage{algorithm} without loading an algorithmic engine like usepackage{algpseudocode}. |
Add usepackage{algpseudocode} directly after usepackage{algorithm} in the preamble. |
| Algorithm reference shows section number (e.g., “Algorithm 2” instead of “Algorithm 1”) | label{...} was placed before caption{...} or outside the algorithm float environment. |
Move label{alg:...} immediately after caption{...} inside the float block. |
Missing line breaks in algorithm2e output |
Omitting the mandatory semicolon (;) macro at the end of algorithmic lines. |
Append ; to the end of every statement inside the algorithm2e body. |
| Float spills over column boundaries in two-column layouts | Standard algorithm float is constrained to a single column width in two-column journal templates (IEEEtran, ACM). |
Use the starred environment begin{algorithm*} ... end{algorithm*} to span across both columns. |
| Algorithm drifts to manuscript end | LaTeX default float placement parameters cannot satisfy page budget constraints. | Load usepackage{float} and specify the strict placement modifier begin{algorithm}[H] to force inline positioning. |
Free alternatives (table)
Researchers can select among several free, open-source packages and tools to format algorithms and software code in academic publications:
| Package / Tool | Primary Purpose | Float Container Included | Line Numbering Support | Best Use Case |
|---|---|---|---|---|
| algorithmicx (algpseudocode) | Typesetting high-level pseudocode with modern syntax | No (requires algorithm package) |
Yes (optional argument [1]) |
Standard scientific manuscripts, journal articles, and graduate theses. |
| algorithm2e | Self-contained, customizable algorithm layout | Yes (monolithic float environment) | Yes (package option linesnumbered) |
Complex computational pipelines requiring vertical line connectors and compact syntax. |
| algorithms (legacy algorithmic) | Classic pseudocode typesetting (older CTAN bundle) | Yes (includes algorithm.sty) |
Yes (integer step argument) | Maintaining legacy LaTeX templates or backward compatibility with older conference styles. |
| listings | Typesetting verbatim source code across 50+ languages | Optional (via float parameter) |
Yes (via numbers=left) |
Displaying actual runnable software implementations (e.g., Python, C++, R) rather than pseudocode. |
| minted | Syntax-highlighted source code via Pygments engine | Optional (via listing float) |
Yes (via linenos option) |
Technical documentation and reports requiring colorized, high-fidelity code display. |
When preparing manuscripts with extensive codebases, managing reference databases with dedicated tools such as Zotero vs JabRef for LaTeX-based writing ensures that software citations and package DOIs remain consistent across revisions.
FAQ
How do I enable line numbering in a LaTeX algorithm?
In algorithmicx with algpseudocode, pass the line-numbering frequency as an optional argument to the environment: begin{algorithmic}[1] numbers every line, while begin{algorithmic}[5] numbers every fifth line. In algorithm2e, pass linesnumbered in the package declaration: usepackage[linesnumbered]{algorithm2e}.
What is the difference between algorithmicx and algorithm2e?
The algorithmicx package separates the floating figure-like box (provided by algorithm.sty) from the algorithmic pseudocode keywords (provided by algpseudocode.sty), offering modularity and widespread compatibility with journal templates. The algorithm2e package is an all-in-one system that provides its own floating environment, custom vertical lines (vlined), and distinct commands (such as KwData and KwResult).
Why does my algorithm cross-reference show the section number instead of the algorithm number?
This error occurs when the label{...} command is placed before the caption{...} command or outside the algorithm float environment. In LaTeX, caption updates the internal reference counter; placing label after caption ensures that ref{...} correctly extracts the algorithm index.
How do I format algorithms across two columns in IEEE or ACM conference papers?
In two-column document classes (such as documentclass[conference]{IEEEtran} or documentclass[sigconf]{acmart}), a wide algorithm will be clipped if placed in a standard single-column float. Use the starred environment begin{algorithm*} ... end{algorithm*} to make the algorithm span across both columns at the top or bottom of the page.
Can I display actual runnable programming code instead of pseudocode?
Yes. If your manuscript requires displaying real programming code with exact syntax rather than conceptual pseudocode, use the listings package or minted package instead of algpseudocode. These packages preserve whitespace, handle language keywords automatically, and avoid interpreting programming symbols as LaTeX commands.
Sources (official docs)
- Comprehensive TeX Archive Network (CTAN). (2005). The algorithmicx package (Szász János, Version 1.2). Retrieved November 8, 2026, from https://ctan.org/pkg/algorithmicx
- Comprehensive TeX Archive Network (CTAN). (2017). The algorithm2e package (Christophe Fiorio, Version 5.2). Retrieved November 8, 2026, from https://ctan.org/pkg/algorithm2e
- Comprehensive TeX Archive Network (CTAN). (2009). The algorithms bundle (Peter Williams and Rogério Brito). Retrieved November 8, 2026, from https://ctan.org/pkg/algorithms
- Overleaf. (2026). Algorithms – Overleaf, Online LaTeX Editor Documentation. Digital Science. Retrieved November 8, 2026, from https://www.overleaf.com/learn/latex/Algorithms







