Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add comments on an algorithm environment in LaTeX?

I am using LaTeX to write a pseudo algorithm using the algorithm package. I want to add comments on the code in a way that they get aligned. The following lines are what I could do, but the comments are not aligned. How do I do that?

\begin{algorithm}[H]
\caption{}
\label{}
    \begin{tabbing}
     quad \=\quad \=\quad \kill
     \keyw{for} each a $\in$ A \keyw{do} \\
     \> command; \qquad \qquad $\blacktriangleright$ add text here \\
     \keyw{end} \\

\end{tabbing}
\end{algorithm}

The comments are like that:
 one comment here\\
               other here\\
     other here\\

How do I align them?

like image 736
Diego Avatar asked Nov 05 '25 14:11

Diego


1 Answers

If you're setting algorithms, use a dedicated pseudo code setting package. Here's one using algorithmicx's algpseudocode:

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode}

\algnewcommand{\algorithmicforeach}{\textbf{for each}}
\algdef{SE}[FOR]{ForEach}{EndForEach}[1]
  {\algorithmicforeach\ #1\ \algorithmicdo}% \ForEach{#1}
  {\algorithmicend\ \algorithmicforeach}% \EndForEach

\begin{document}

\begin{algorithm}
  \caption{An algorithm}
  \begin{algorithmic}[1]
    \ForEach{$a \in A$}%
      \State command \algorithmiccomment{This is a comment}
      \State another command \algorithmiccomment{This is another comment}
    \EndForEach
  \end{algorithmic}
\end{algorithm}

\end{document}

algpseudocode already defines \ForAll. However, in the above code, I copied that definition into \ForEach. Comments can be added using \algorithmiccomment. Formatting and placement can be modified.

like image 150
Werner Avatar answered Nov 07 '25 04:11

Werner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!