15

I am using the algorithm2e package to write a pseudo code algorithm. I would like to add a comment with \tcp, on the same line as an \If statement. I managed to do so by putting the \tcp command between parenthesis right after the \If, but it introduces a vertical space between the If and the following line.

\usepackage[titlenumbered,ruled,noend,algo2e]{algorithm2e}
\usepackage{algorithm}

\begin{document}
    \begin{algorithm}[t]
        \If(\tcp*[l]{comment}){$k = K$}{do stuff}
        \If{$k \neq K$}{do other stuff}
    \end{algorithm}
\end{document}

Results in:

enter image description here

Anyone knows how to fix that?

1 Answer 1

19

You should use the [h] specification of \tcp*, as explained here at page 32.

\documentclass{article}
\usepackage[titlenumbered,ruled,noend,algo2e]{algorithm2e}
\usepackage{algorithm}

\begin{document}
    \begin{algorithm}[t]
        \If(\tcp*[h]{comment}){$k = K$}{do stuff}
        \If{$k \neq K$}{do other stuff}
    \end{algorithm}
\end{document}

enter image description here

1
  • 14
    As an addendum: if you wish your comment to show up at the right edge of the algorithm, rather than right next to the text, use [f] instead (as also explained on the same page) Dec 2, 2018 at 13:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .