5

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?

7

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

  • 4
    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) – Adarain Dec 2 '18 at 13:32

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.