How to Typeset Algorithms and Pseudocode in LaTeX
Explain how to write algorithms in LaTeX: use the `algorithm` float with `algorithmic` structure commands for numbered pseudocode, use `listings` to typeset real source code, and give methods for checking numbering, references, and errors.
Key Points of This Article
- Wrap pseudocode in an algorithm float environment around the algorithmic structural commands, so that it is automatically numbered, given a caption, and can be cross-referenced in the body text.
- Real source code (Python, C++, etc.) should be typeset with listings, which preserves characters and supports syntax highlighting; its requirements differ from those of pseudocode.
- Structures such as \If and \For in algorithmic must be written in pairs with their corresponding End commands; omitting one causes subsequent typesetting to become disordered.
- If cross-references show question marks after compilation, compiling twice in a row usually resolves the problem; if it still fails, check the spelling of the label.
- LaTeX source files containing algorithms that are to be translated require item-by-item verification of keywords and symbols, and machine translation results need manual review.
Many people writing papers or technical reports need to include an algorithm description in LaTeX. It needs a number and a title, the body text must be able to refer to "Algorithm 1", and the internal indentation has to show loops and branches. This differs from both ordinary paragraphs and ordinary monospaced code, and simply pasting the text rarely produces a good layout. Essentially, writing algorithms in LaTeX is solved with two layers: a floating environment plus algorithmic structure commands.
After reading this, you will be able to choose the right package, follow the steps to write a piece of pseudocode that compiles, and know how to check numbering, references, indentation, and errors. The article also distinguishes between two needs, "pseudocode" and "source code," because how to typeset code in LaTeX and how to write an algorithm are two different things; using the wrong tool will make the work much harder.
How to choose a method for typesetting algorithms in LaTeX? One-sentence conclusion
Pseudocode is written with the algorithm float environment together with algorithmic or algpseudocode; when you need to show real source code, typeset it with listings. The table below gives recommended approaches for your situation.
| Your situation | Recommended Practices | Cause |
|---|---|---|
| Pseudocode in the paper needs numbering, a caption, and references in the body text | algorithm float + algpseudocode | Automatic numbering of floating environments, referenced with \ref, and also able to generate a list of algorithms |
| The user says: "Used to textbook style, hope to use keywords like \KwIn, \KwOut" — translate to English. I used to the textbook style; I'd like to use keywords like \KwIn and \KwOut. | algorithm2e | Grammar stays close to the textbook; sentences end with semicolons. |
| I need to show real Python or C++ source code | lstlisting environment | Preserve source code characters, support syntax highlighting and line numbers |
| Only one or two lines of symbol notes are needed; no numbering is required. | Regular paragraph with inline formula | No need to introduce floating elements; the code is simple to write. |
| The journal or school template has already specified the package | Subject to the template requirements. | Templates are usually already formatted, so changing them without permission can easily cause conflicts. |
Before You Begin: Confirm These Points
First distinguish pseudocode from source code. The goal of pseudocode is to let readers follow the idea; it does not need to be runnable, and keywords and mathematical symbols may be mixed freely. Source code must be preserved character for character: indentation, spaces, and comments must all be kept as they are. The two use different formatting tools, and mixing them makes the formatting hard to control.
Confirm that the compilation environment already has the required packages. The algorithm, algorithmic, and algpseudocode packages are commonly used packages in mainstream LaTeX distributions. If compilation reports that a file cannot be found, install the missing package with the distribution's own package manager, and do not rush to change the body text.
Check whether the template has already loaded the relevant packages. Many journal templates already define algorithm environments or keyword commands. Loading different algorithm packages again can easily cause command conflicts, so the syntax provided by the template should be followed in such cases.
Plan numbering and cross-references in advance. Papers usually require numbered algorithms such as "Algorithm 1", and the main text must be able to refer to them. Each algorithm's label must be unique; it is advisable to use a prefix, for example starting with alg:, to make later lookup easier.
If source files containing algorithms are to be translated into other languages, time must be reserved for verification. Translations may alter keywords, variable names, or symbols, so they need to be checked paragraph by paragraph against the original. Both machine translation and OCR output should be manually reviewed for important content.
Steps to Write a Numbered Pseudocode Block in LaTeX
- Load the packages in the preamble: include the two packages algorithm and algpseudocode. algpseudocode automatically loads the underlying support needed for the structural commands, so generally these two lines are all that is required.
- In the body, wrap the entire algorithm in the algorithm environment, with the positional argument written as [htbp], letting the typesetting system choose a suitable placement on its own.
- Inside the algorithm environment, write \caption to give the algorithm a title, and immediately after it write \label to set a label; it is recommended that the label name carry the alg: prefix.
- After the caption, open the algorithmic environment. The number in square brackets indicates how often line numbers are shown (every how many lines); [1] is commonly used to number every line.
- Use \Require for inputs, \Ensure for outputs, and \State for ordinary statements. Each statement goes on its own line, and no semicolons are needed.
- Use \If{condition} with \EndIf, \For{range} with \EndFor, and \While{condition} with \EndWhile to write control structures; the statements in between are indented automatically. Use \Return to write the return value.
- Close the algorithmic and algorithm environments in turn. In the body, refer to the algorithm number with \ref{alg:label-name}, then compile twice in a row so that the cross-references take effect.
Verify item by item after completion
After receiving the PDF, don't just check whether it compiles successfully; also go through each of the following points one by one.
| Inspection item | How do you see it? | What should I do if I have a problem? |
|---|---|---|
| Number and Title | Does the top of the algorithm display "Algorithm 1" and the title text? | Check whether \caption is placed before the algorithmic environment; if it is in the wrong position, the caption will be missing. |
| Cross-reference | Do citations in the body text display as actual numbers rather than question marks? | Compile twice in a row; if it still fails, check that the spelling of \label and \ref matches exactly. |
| Indentation and End Markers | Does every \If and \For have a corresponding End command? | Missing end commands can cause all subsequent content to be indented or lead to direct errors; add them one by one. |
| Symbols and Formulas | Are variables, subscripts, and Greek letters in math mode? | Wrap it in $...$ to keep letters and symbols from crowding together |
| Pagination position | Is the algorithm block split across two pages, or is it too far from the text that references it? | Adjust the [htbp] placement parameter, or split the overly long algorithm into two smaller algorithms. |
| "Content after translation or export" | Are keywords, variable names, and identifiers/numbers preserved? | Check paragraph by paragraph against the original text, focusing on whether keywords such as \Require and \Ensure have been altered. |
📊 Core Comparison
Algorithm typesetting usually follows three mainstream styles, each with its own emphasis. The table below will help you choose.
| Method | Suitable content | Grammar style | Things to note |
|---|---|---|---|
| algorithmic and algpseudocode | Pseudocode in the paper, emphasizing clear structure | Structural commands come in pairs, such as \If corresponding to \EndIf. | The end command must not be left out; indentation is handled automatically by the environment. |
| algorithm2e | Textbook or lecture-notes style; standard input and output keywords are needed. | Statements end with a semicolon; keywords such as \KwIn, \KwOut | It may conflict with some journal templates, so please confirm the template requirements before use. |
| listings (lstlisting environment) | Real Python, C++ and Other Source Code Examples | Preserve the source code character for character, with syntax highlighting and line numbers. | It is a source code display tool and is not responsible for structural indentation of pseudocode. |
If you have a complete LaTeX source package and need to translate the paragraphs containing algorithms into another language, you can consider the document translation feature of OmniDoc. It supports LaTeX source packages, and the output will try to preserve formulas and layout, but the keywords and symbols in the algorithms still need to be checked item by item. In addition, the UniDoc web editor (app.unidoc.top) supports conversion between Word and LaTeX. It is suitable for organizing content there first and then exporting it back to LaTeX source files. Compilation and final typesetting should still be based on your local LaTeX environment.
❓ Frequently Asked Questions (FAQ)
1. How do I add an algorithm table in LaTeX? Is it the same thing as an algorithm block?
The so-called "algorithm table" usually refers to the algorithm float, which is a numbered and captioned algorithm block, not a tabular table. If you want to list all algorithms at the end of the document, you can use \listofalgorithms to generate a list of algorithms; likewise, you need to compile twice.
2. How to typeset code in LaTeX, and why not just use the pseudocode environment directly?
The algorithmic package is intended for structured pseudocode. It does not provide syntax highlighting and cannot always guarantee that source characters are preserved exactly. For real source code, listings is recommended: it does not depend on external programs and its syntax is straightforward. minted produces better results, but it requires Python and Pygments to be installed on the system and shell-escape to be enabled during compilation, and misconfiguration can easily lead to errors.
3. What should I do if "Undefined control sequence" appears after compiling?
This usually means that a command is not being recognized, most likely because the package was not loaded or the command is misspelled. Check the spelling of commands such as \State and \EndIf one by one, and confirm that algpseudocode is loaded in the preamble. If it conflicts with the template, simply follow the syntax used in the journal's or university's template.
4. Can pseudocode be written in Chinese?
Yes, but Chinese support must be configured first, and you need to choose a compilation method that can handle Chinese. Keywords are best kept in English, with Chinese used only for explanatory text and variable annotations, so that readers can more easily compare them with the notation used in other literature.
📝 Summary
How to write algorithms in LaTeX: the core approach is to wrap the algorithmic structure commands in the algorithm floating environment, and use \caption and \label to achieve numbering and cross-referencing. Real source code is typeset with listings; the two are handled separately, which makes the formatting easier to control. After writing, check the numbering, references, closing commands, and symbols item by item in a table, and you will get a standard algorithm layout.
Open OmniDoc to edit, convert, or translate your LaTeX documents


