0
How does this loop work and what is the use of continue?
int i=1;for (;i<100;i++){ if (i>5) continue; i*=i;}cout << i
3 Answers
+ 3
int i = 1
is i < 100? Yes
is i > 5? No
i*=i = 1
i++ = 2
is i < 100? Yes
is i > 5? No
i*=i = 4
i++ = 5
is i < 100? Yes
is i > 5? No
i*=i = 25
i++ = 26
is i < 100? Yes
is i > 5? Yes
Continue (skip i*=i)
Since from this point on, i is always going to be greater than 5, i*=i will not execute again. The final value of i would be 100, where the next iteration would be where i > 100
0
This (for) loop is checking whether or not (i < 100). If it is, it will go forward with the code in the body. If it's not, it will not go forward, and simply cout (i).
After finishing the code in the body it will increment (i) by 1, and test again whether or not (i < 100). It will repeat this until (i < 100) evaluates to false.
The use of continue in a loop such as (for), means to skip to the next iteration of the loop, without finishing the rest of the loop's body. In this case, it will continue when (i > 5). If (!(i > 5)), then it multiply (i) by itself.
As soon as (i > 100), the (for) loop evaluates to false, and the loop finishes, where it can then cout (i).
- 1
How would it run step by step?