20

I could not find in the manual how to increment a for loop in the algorithm2e package.

I want to something like this:

for(i=0; i<10, i=i+2){
 do something;
}

2 Answers 2

33

Somehow algorithm2e has \KwTo but not \KwBy. It is easy to define it, however:

\documentclass{article}

\usepackage{algorithm2e}
\pagestyle{empty}
\SetKw{KwBy}{by}
\begin{document}
\begin{algorithm}
  \For{$i\gets0$ \KwTo $8$ \KwBy $2$}{
    Do something
    }
\end{algorithm}
\end{document}

enter image description here

14

You can redefine the way \For works:

enter image description here

\documentclass{article}

\usepackage[noline]{algorithm2e}

\SetKwFor{For}{for (}{) $\lbrace$}{$\rbrace$}

\begin{document}

\begin{algorithm}
  \For{$i = 0;\ i < 10;\ i = i + 2$}{
    Do something\;
  }
\end{algorithm}

\end{document}
3
  • How do I add multiple lines in the for loop? Using \; after each statement doesn't work, they just get concatenated into a long line Commented Apr 28, 2020 at 10:24
  • This is what I get with this code. I can add multiple lines without problem. Perhaps show a complete, minimal example that replicates your issue. Commented Apr 28, 2020 at 17:55
  • I managed to fix it by adding a whitespace between the end of line and \; Commented Apr 28, 2020 at 23:22

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.