LaTeX: How to write algorithm?

There are different packages that help writing algorithms on LaTeX. I will be using algorithm2e package for writing algorithm in LaTeX. This package should work fine if you have installed ‘TeX Live Full‘. Otherwise, you may get error while using algorithm2e package. If you get an error then you need to install the package ‘texlive-science‘ which includes algorithm2e package.

On Ubuntu, you can install texlive-science package with the following command:


sudo apt-get install texlive-science

Here is the complete LaTeX code that has examples on writing algorithm using algorithm2e package. The first algorithm has While loop along with If/Else condition. The second algorithm example has nested ForEach loop with If/ElseIf/Else condition inside it.


\documentclass{article}

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

\begin{document}

\section{Algorithm Examples}

% Algorithm 1: While loop example with If/Else condition

\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwResult{Write here the result}
\SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output}
\Input{Write here the input}
\Output{Write here the output}
\BlankLine

\While{While condition}{
    instructions\;
    \eIf{condition}{
        instructions1\;
        instructions2\;
    }{
        instructions3\;
    }
}

\caption{While loop with If/Else condition}
\end{algorithm}

\bigskip % add 12pt space in-between

% Algorithm 2: Nested ForEach loop example with If/ElseIf/Else condition

\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwResult{Write here the result}
\SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output}
\Input{Write here the input}
\Output{Write here the output}
\BlankLine

$x\leftarrow 0$ \;
$y\leftarrow 0$ \;
\BlankLine
\ForEach{ForEach condition}{    
    
    \BlankLine
    
    \tcc{comments on code}  
    \ForEach{ForEach condition}{
        \If{If condition}{
            instruction(s) like below: \\
            increase $x$ by $1$\;
            decrease $y$ by $2$\;
        }
                
        \BlankLine
        
        \uIf{If condition}{
            instruction
        }
        \uElseIf{ElseIf condition}{
            instruction
        }
        \uElse{
            instruction
        }               
    }   
}
\caption{Nested ForEach loop with If/ElseIf/Else condition}
\end{algorithm}

\end{document}

Below is the pdf file generated after you compile the above LaTeX source:

Hope this helps.
Thanks.