Now we are going to discuss a very interesting topic, which is how to write if-else statements for algorithms in LaTeX.

You already know that LaTeX is not only for writing equations and text. It also provides excellent features for formatting and displaying algorithms.

We will now go step by step and discuss each part in detail.

The Algorithm environment

This is the most widely used method, especially in research papers and theses. In this environment we use commands such as \If, \Else, and \ElsIf.

\usepackage{algorithm,algpseudocode}
\If{$x > 0$}
    \State print("Positive")
\ElsIf{$x = 0$}
    \State print("Zero")
\Else
    \State print("Negative")
\EndIf
\If{$x > 0$}
This begins a conditional block. The condition inside is typeset in math mode, so it looks neat but is not actually evaluated.
\State print("Positive")
Represents a single action inside the block. The \State command ensures proper indentation and formatting.
\ElsIf{$x = 0$}
Adds an alternative condition. It is formatted in math mode but has no logical evaluation, only visual representation.
\Else
Starts the default block that is shown if none of the previous conditions hold. It also uses \State for actions.
\EndIf
Closes the entire conditional block. Every \If must be paired with a matching \EndIf.
\documentclass{article}

\usepackage{algorithm}
\usepackage{algpseudocode}

\begin{document}

\begin{algorithm}
\caption{Check Number Sign}
\begin{algorithmic}
\If{$x > 0$}
    \State print("Positive number")
\ElsIf{$x = 0$}
    \State print("Zero")
\Else
    \State print("Negative number")
\EndIf
\end{algorithmic}
\end{algorithm}

\end{document}

The algorithm2e package

This one is much more flexible and popular. Its syntax looks almost the same as a real programming language.

\If{$x > 0$}{
    print("Positive")
}
\ElseIf{$x = 0$}{
    print("Zero")
}
\Else{
    print("Negative")
}
\If{$x > 0$}{ ... }
Begins an if-block. The condition {$x > 0$} is written in math mode, and the body of the block goes inside the second braces { ... }.
\ElseIf{$x = 0$}{ ... }
Starts an else-if block. The condition {$x = 0$} is checked, and if true, the statements inside { ... } are executed.
\Else{ ... }
Defines the else block, which runs if none of the previous conditions are satisfied. The braces { ... } contain the default actions.
\documentclass{article}

\usepackage[linesnumbered,ruled,vlined]{algorithm2e}

\begin{document}

\begin{algorithm}
\caption{Check Number Sign}
\If{$x > 0$}{
    print("Positive number")
}
\ElseIf{$x = 0$}{
    print("Zero")
}
\Else{
    print("Negative number")
}
\end{algorithm}

\end{document}

Share tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *