4

Using the algorithmicx it is pretty easy to turn on or off line numbering or to number every n-th line. Taking this MWE (taken from the doc)

\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\begin{document}
\begin{algorithm}[H]
\caption{Euclide's algorithm}\label{euclid}
\begin{algorithmic}[5]
\Procedure{Euclide}{$a,b$}\Comment{The g.c.d. of a and b}
   \State $r\gets a\bmod b$
   \While{$r\not=0$}\Comment{We have the answer if r is 0}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
   \EndWhile\label{euclidendwhile}
   \State \Return $b$\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}

In this example, the first numbered line is the 5-th. Is there a way to turn on the numbering on the first line ?

Subsequent question, is it possible to turn the numbering on any arbitrary line ?

4

You will have to update a specific macro to change the condition of printing:

enter image description here

\documentclass{article}
\usepackage{algpseudocode,algorithm}

\makeatletter
\def\ALG@step%
   {%
   \stepcounter{ALG@line}%
   \stepcounter{ALG@rem}%
   \ifnum\value{ALG@line}=1
     % Print line number if it is 1
     \alglinenumber{\arabic{ALG@line}}%
   \else\ifnum\value{ALG@rem}=\ALG@numberfreq
     % Print line number if the ALG@rem = \ALG@numberfreq
     \setcounter{ALG@rem}{0}\alglinenumber{\arabic{ALG@line}}%
   \fi\fi
   }%
\makeatother

\begin{document}
\begin{algorithm}[H]
  \caption{Euclide's algorithm}\label{euclid}
  \begin{algorithmic}[5]
    \Procedure{Euclide}{$a,b$}\Comment{The g.c.d.\ of~$a$ and~$b$}
       \State $r \gets a \bmod b$
       \While{$r \neq 0$}\Comment{We have the answer if~$r$ is~$0$}
          \State $a \gets b$
          \State $b \gets r$
          \State $r \gets a \bmod b$
       \EndWhile\label{euclidendwhile}
       \State \Return $b$\Comment{The g.c.d.\ is~$b$}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}
\end{document}

The adjustment to \ALG@step inserts a condition to check whether the line number is 1, and printing accordingly.

In general it would be possible to turn on the numbering on any arbitrary line, but the code is not set up for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.