[Tex/LaTex] How to add line numbers to the Algorithm in Latex

algorithmsline-numbering

I am writing an algorithm. I am already using the following packages for algorithms:

\usepackage{algorithmic}
\usepackage{algorithm}
\usepackage{amsmath}

I am also using the \STATE tag. I tried to add the package \usepackage{algpseudocode} it started giving errors.

Best Answer

The algorithmic environment takes an optional argument. The optional argument is a number that defines the skip between line numbering. The default [0] implies no line numbering, while [1] puts a line number on every line. [2] puts a line number every second line, and so forth:

enter image description here

\documentclass{article}

\usepackage{algorithm,algorithmic}

\begin{document}

\begin{algorithm}
  \caption{An algorithm}
  \begin{algorithmic}
    \IF{some condition is true}
      \STATE do some processing
    \ELSIF{some other condition is true}
      \STATE do some different processing
    \ELSIF{some even more bizarre condition is met}
      \STATE do something else
    \ELSE
      \STATE do the default actions
    \ENDIF
  \end{algorithmic}
\end{algorithm}

\begin{algorithm}
  \caption{An algorithm}
  \begin{algorithmic}[1]
    \IF{some condition is true}
      \STATE do some processing
    \ELSIF{some other condition is true}
      \STATE do some different processing
    \ELSIF{some even more bizarre condition is met}
      \STATE do something else
    \ELSE
      \STATE do the default actions
    \ENDIF
  \end{algorithmic}
\end{algorithm}

\begin{algorithm}
  \caption{An algorithm}
  \begin{algorithmic}[2]
    \IF{some condition is true}
      \STATE do some processing
    \ELSIF{some other condition is true}
      \STATE do some different processing
    \ELSIF{some even more bizarre condition is met}
      \STATE do something else
    \ELSE
      \STATE do the default actions
    \ENDIF
  \end{algorithmic}
\end{algorithm}

\end{document}
Related Question