why output 100? #include <iostream> using namespace std; int main() { int x=1; for(;x<100;x++) {if(x>5) continue; x*=x; } cout<<x; } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why output 100? #include <iostream> using namespace std; int main() { int x=1; for(;x<100;x++) {if(x>5) continue; x*=x; } cout<<x; }

23rd Aug 2016, 3:47 AM
Lekhraj Singh
Lekhraj Singh - avatar
2 Answers
+ 6
The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. The 1st time x=1 => x= 1*1=1 The 2nd time x increases by one so x=2 and x= 2*2=4 The 3rd time x increases by one so x=5 and x= 5*5=25 The 4th time x increases by one so x=26 which is greater than 5 so the continue statement executes. It skips the code after the continue statement and forces the next iteration of the loop. The 5th time x increases by one so x=27 which is greater than 5, the continue statement executes and so on until 100 in which the condition x<100 is false, the for loop stops execution and the last command cout<<x outputs the last value of x which is 100. To understand it even better put 2 commands cout<<x<<endl; in the loop and execute. I give you the code below: #include <iostream> using namespace std; int main() { int x=1; for(;x<100;x++) { if(x>5) { cout<<x<<endl; continue; } x*=x; cout<<x<<endl; } cout<<x; }
23rd Aug 2016, 5:19 AM
GTimo
GTimo - avatar
0
thanks Giannis 👍
23rd Aug 2016, 6:16 AM
Lekhraj Singh
Lekhraj Singh - avatar