[Tex/LaTex] do-while loop in algorithm2e

algorithm2epseudocode

I am using

\usepackage[norelsize, linesnumbered, ruled, lined, boxed, commentsnumbered]{algorithm2e}

\RestyleAlgo{boxruled}

It seems that algorithm2e has the default repeat-until construct.
But I want to use do-while construct as do something while(u is not v).

The repeat-until construct is different from the do-while construct.

My search resulted in do-while loop in pseudo code. But the answer is for algorithmicx.

How this can be done in `algorithm2e?

Best Answer

You can create a do-while construct using the same technique that a repeat-until construct is generated. They both fall under what algorithm2e calls "Repeat macros":

\SetKwRepeat{Do}{do}{while}

The above now allows you to use

\Do{<end condition>}{<stuff>}

Here is a minimal example showing its use/output:

enter image description here

\documentclass{article}
\usepackage[linesnumbered, ruled]{algorithm2e}
\SetKwRepeat{Do}{do}{while}%
\begin{document}

\begin{algorithm}[H]
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  initialization\;
  \While{not at end of this document}{
    read current\;
    \Repeat{this end condition}{
      do these things\;
    }
    \eIf{understand}{
      go to next section\;
      current section becomes this one\;
    }{
      go back to the beginning of current section\;
    }
    \Do{this end condition}{
      do these things\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}

\end{document}
Related Question