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?

3

1 Answer

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

\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.

2

Your Answer

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

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest