2

I'm having this code

\documentclass[11pt,a4paper]{article}
\usepackage[]{algorithm2e}

\begin{document}
\begin{algorithm}[H]
                \If{cond}{
                        stmt1\;
                }
\end{algorithm}
\end{document}

Which gives me this:

This makes some algorithms much shorter, I'm searching for a way to get rid of the newline after the then (for ifs where the body is only a oneliner). Is this possible with algorithm2e and if yes how?

1 Answer 1

4

For a one line if-statement you can use \lIf (line if). The semicolon is added automatically.

\documentclass[11pt,a4paper]{article}
\usepackage{algorithm2e}

\begin{document}
\begin{algorithm}
                \If{cond}{
                        stmt1\;
                }
                \lIf{cond}{
                        stmt2
                }
                other things
\end{algorithm}
\end{document}

enter image description here

See page 32 of the package manual for the different macros for if-then-else constructs.

3
  • Thanks, should then the then line text also not end with \; ? (with it there is an empty newline after the then is this normal?)
    – atticus
    Jul 31, 2020 at 11:50
  • 1
    I think \; is only needed to separate the lines of a multi-line block, so it is not needed in a single-line if-statement. Maybe (but that's just speculation, I didn't check it) a \; is interpreted as a line ending, whereas a single-line if-statement has an automatic line ending already, resulting in two consecutive line endings and therefore an empty line.
    – Marijn
    Jul 31, 2020 at 12:17
  • Ok, thank you ;)
    – atticus
    Jul 31, 2020 at 12:26

You must log in to answer this question.

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