1

Here is the code, I have tried:

 \documentclass[smallextended]{svjour3}       % onecolumn (second format)
 \usepackage[linesnumbered,lined,boxed,algoruled,linesnumbered]{algorithm2e}
 \begin{document}
 \begin{algorithm}[H]
 \For {i in range(10)} {


  \If{i==2}
  {
  print value of i=2;
  \If{i==4} /* giving error*/
  { 
  print value of i=4;
  }
 } 
 \uIf {flag==1} { print 1;
 }


 \uIf {flag==2} { print 2;   
 }
 \uIf {flag==3} { print 3;   /* giving error*/
 }
 \Else { do something else;
 }
 }
 \end{algorithm}
 \end{document}

How to resolve nested if and else if errors?

1
  • Welcome to TeX. SE! Pplease extend your code fragment to complete small document beginning with \documentclass and ending with \end{document} For start also remove all empty lines in your code. Commented Jun 25, 2019 at 3:16

1 Answer 1

2

With algorithm2e lines must be ended by \; (with the preceding \), or, if you want a comment, lines must be ended with one of the line-ending comment macros \tcc*[r], \tcc*[l] (C style /* */ right and left aligned) or \tcp*[r] and \tcp*[l] (C++ style // right or left aligned). From the manual on page 4:

Very Important: each line MUST end with \; only those with a macro beginning a block should not end with \;.

See also section 10.3 on page 32 for the comment syntax.

Note that at the end of a block it is not really necessary to end a line with \; because the block also ends the line (see the example below in the second nested if statement). However, if you always end the line with this you can't forget it in other cases where it is essential.

MWE:

\documentclass[smallextended]{svjour3}       % onecolumn (second format)
\usepackage[linesnumbered,lined,boxed,algoruled,linesnumbered]{algorithm2e}
\begin{document}
\begin{algorithm}[H]
\SetNoFillComment
\For {i in range(10)} {
\If{i==2}
{
    print value of i=2\;
    \If{i==4}{ 
        print value of i=4\tcc*[l]{giving error}
        \If{i=$\sqrt{-1}$}{
            print I'm aginary!
        }
    }
} 
\uIf {flag==1} { print 1\;
}


\uIf {flag==2} { print 2\;   
}
\uIf {flag==3} { print 3\tcc*[l]{giving error}
}
\Else { do something else\;
}
}
\end{algorithm}
\end{document}

Note the command \SetNoFillComment at the start of the algorithm, this prevents the closing */ to stretch to the right margin. You can also set this globally using the nofillcomment package option.

Result:

enter image description here

2
  • OP example will work fine if (s)he will move /* giving error*/ from 4th line on the end of the 5th line. Nice answer (+1)! Commented Jun 25, 2019 at 8:40
  • Thanks for such a great explanation Commented Jun 26, 2019 at 18:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.