Converting a for loop into a while loop with post-increment

Viewed 51

What would be the equivalent of doing the following for loop as a while loop?

for (int i=0;i<10;i++)
{
    ...
}

At first I thought the following would work:

int n = 0;
while (n++ <= 10) 
{
    ...
}

But it seems that the post-increment happens before the first while loop is entered, and so I'd need to set n=-1 to adjust for that. Is there a closer way to re-write a for loop into a while loop (without the do) ?

3 Answers

You would have to put the increment inside the body of the loop (at the very end thereof):

int n = 0;
while (n < 10) 
{
    //...
    n++;
}

But note well: As mentioned in the comments, any continue statement inside such a loop (if not itself enclosed in a nested, inner loop) will break the code and create a potentially infinite loop!

Moral of the Story: Use a for loop when a for loop is appropriate, and a while loop when a while loop is appropriate.

There's two way to do it.

  1. while loop
  2. do-while loop

Try following source code

int n=0;
while(n <= 10){
      //do your task here
      n++;
}

do-while

int n=0;
do{
      //do your task here
      n++;
}while(n <= 10)

If you want a post-increment while loop then use (n - 1) inside the while loop or you can create a temporary variable too.

int n = 0;
while(n++ < 10){
   // use n - 1
}

or,

int n = 0;
while(n++ < 10){
   int tn = n - 1; // use tn instead of n - 1
}
Related