2

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) ?

2
  • 1
    do is a while loop, use that. Commented Jan 17, 2021 at 4:52
  • Not for the forward loop, though int n = 10; while(n--) {...} will work in reverse. However, any such rewrite will extend the scope and lifetime of n beyond the loops. Commented Jan 17, 2021 at 4:52

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

With the caveat that any accidental continue; would make it an infinite loop.
@dxiv Very good point. In fact, even a deliberate continue would do the same!
1

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)

1 Comment

Both loops go too far by one. And anyway the OP asked for no do. If you are to use it then int n=0; do {...} while(n++ < 10) works.
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.