0
\begin{algorithm}[h]
   \caption{Transformation}
   \tcp{Apply transformation X comment1}
   \For{$k=1$ \KwTo $n$} 
   {$P=A*P*A^{T}$ \tcp{comment 2}}
\end{algorithm}

I want to add a comment in for loop line.

5
  • Do you mean a comment in the source code (using % ), or a comment, readable in the Latex-output?
    – MS-SPO
    Sep 17, 2021 at 15:08
  • comment readable in the Latex output...
    – Wang
    Sep 17, 2021 at 15:15
  • \For{$k=1$ \KwTo $n$} \\ this is for loop
    – Wang
    Sep 17, 2021 at 15:15
  • want to comment in this way
    – Wang
    Sep 17, 2021 at 15:16
  • Hm, a good starting point is to provide complete minimal code, i.e. which can be copied and run right away. The fragment simply can't, for obvious reasons. Thanks
    – MS-SPO
    Sep 17, 2021 at 17:57

2 Answers 2

2

The first answer forces the do into the next line. This solution here doesn't:

\documentclass{article}
\usepackage{algorithm2e}

\begin{document}
    \begin{algorithm}[h]
       \caption{Transformation}
       \tcp{Apply transformation X comment1}
       \For(\tcp*[f]{this is for loop}){$k=1$ \KwTo $n$} 
        {$P=A*P*A^{T}$ \tcp{comment 2}}
    \end{algorithm}
\end{document}

1
  • 1
    Welcome to TeX.SX!
    – Vincent
    Nov 1, 2021 at 14:58
1

Just place one of the comment macros inside the \For{}-part:

\documentclass{article}
\usepackage{algorithm2e}

\begin{document}
    \begin{algorithm}[h]
       \caption{Transformation}
       \tcp{Apply transformation X comment1}
       \For{$k=1$ \KwTo $n$ \tcp{this is for loop}} 
        {$P=A*P*A^{T}$ \tcp{comment 2}}
    \end{algorithm}
\end{document}

enter image description here

See chapter 10.3 in https://mirror.marwan.ma/ctan/macros/latex/contrib/algorithm2e/doc/algorithm2e.pdf for alternatives.

2
  • Thank you it solve my problem. Is this same applicable when I used \usepackage{algorithm} and \usepackage{algorithmic}. I am finding errors when I used this packages
    – Wang
    Sep 18, 2021 at 2:29
  • The manuals of those packages should tell you, if and how comments are provided. You may also check the "Related" column to the right, search here or search the tags.
    – MS-SPO
    Sep 18, 2021 at 7:47

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.