4
\documentclass[a4paper, 10pt, 3p, final, twocolumn, times]{elsarticle}
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{document}
\begin{algorithm}[htbp]
    \caption{somealg}
    \label{alg}
    \begin{algorithmic}[1]
    \REQUIRE input
    \ENSURE output
    \STATE statement 1
    \FOR {i = 1 to $l$}
    \STATE statement in loop 1
    \STATE statement in loop
    \ENDFOR
    \end{algorithmic}
    \end{algorithm}
\end{document}

I want to add line number in my algorithm and the line number of the statement inside the "for" loop should be 2.1 instead of 3. How should I do? Thank you.

2

The following does not allow for nesting of loop structures within each other, but provides the sub-numbering of a pseudo-code grouping (like \FOR, \WHILE, \LOOP and \REPEAT):

enter image description here

\documentclass{article}

\usepackage{algorithm,algorithmic,xpatch}

\makeatletter
\xpatchcmd{\algorithmic}% <cmd>
  {\arabic{ALC@line}}% <search>
  {\theALC@line}% <replace>
  {}{}% <success><failure>
\xpatchcmd{\algorithmic}{1.2em}{1.5em}{}{}% Increase label width

\newcommand{\updatelinenoprint}{%
  \setcounter{parentcounter}{\value{ALC@line}}% Store current line number
  \setcounter{ALC@line}{0}% Restart line counter
  \renewcommand{\theALC@line}{\theparentcounter.\arabic{ALC@line}}% Update printing mechanism
}
\newcommand{\revertlinenoprint}{%
  \setcounter{ALC@line}{\value{parentcounter}}% Restore original line number
}%

\renewcommand{\theALC@line}{\arabic{ALC@line}}
\newcounter{parentcounter}
\xapptocmd{\algorithmic}{%
  \xapptocmd{\ALC@for}{\updatelinenoprint}{}{}\xpretocmd{\endALC@for}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@whl}{\updatelinenoprint}{}{}\xpretocmd{\endALC@whl}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@loop}{\updatelinenoprint}{}{}\xpretocmd{\endALC@loop}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@rpt}{\updatelinenoprint}{}{}\xpretocmd{\endALC@rpt}{\revertlinenoprint}{}{}%
}
\makeatother

\begin{document}

\begin{algorithm}[htbp]
  \caption{somealg}
  \begin{algorithmic}[1]
    \REQUIRE input
    \ENSURE output
    \STATE statement 1
    \FOR {$i = 1$ to $l$}
      \STATE statement in loop 1
      \STATE statement in loop
    \ENDFOR
    \STATE statement 2
    \WHILE {$i < 10$}
      \STATE statement in loop 1
      \STATE statement in loop
    \ENDWHILE
  \end{algorithmic}
\end{algorithm}

\end{document}

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.