2

I have written the code for if else if block but I want nested if else if loop like

If (flag)
  If (c1) then
    c2
Else
  If (c3) then
    c4
\documentclass{article}
\usepackage[ruled, lined, commentsnumbered, longend]{algorithm2e}

\begin{document}

\begin{algorithm}
\If{(flag)}{
\uIf{c1\;}{c2\;} 
  
 \uElse{
 \uIf{c3\;}
  { c4\;}
  }}
\end{algorithm}
\end{document}

2 Answers 2

2

Don't add extra line ends (\;) within the conditions. And you can use \uIf and/or \uElse to remove the closure.

The following achieves what you're looking for:

enter image description here

\documentclass{article}

\usepackage[ruled, lined, commentsnumbered, longend]{algorithm2e}

\begin{document}

\begin{algorithm}
  \uIf{(flag)}{
    \uIf{(c1)}{
      c2
    } 
  \uElse{
    \uIf{(c3)}{
      c4
    }
  }}
\end{algorithm}

\end{document}
1

I suggest you use algpseudocodex package.

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocodex}
\begin{document}
\begin{algorithm}
\caption{algorithm}
\label{alg}
\begin{algorithmic}[1]
\If{$a=b$}
\If{$a=b$}
\State $a=b$
\ElsIf{$a=b$}
\State $a=b$
\Else
\State $a=b$
\EndIf
\Else
\State $a=b$
\EndIf
\end{algorithmic}
\end{algorithm}
\end{document}

enter image description here

You must log in to answer this question.

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