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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With