+ 1

What is the output of the following code snippet please explain in brief??

for(int i=0;i<8;i++) { if(i==2) { i++; continue; } else if(5*i==20) break; else cout<<5*i; } I need explanation of this code and answer

2nd Feb 2020, 4:17 AM
Manoj
Manoj - avatar
3 Answers
+ 9
manoj marmat continue skips the rest of the code and starts from the top of the loop. break - breaks out of the loop or you could say exits the loop. So in your code it will iterate like this way When i = 0 execute else statement so 5*0 so 0 is printed When i = 1 execute else statement so 5*1 = 5 is printed Now when value of i = 2 then in the if block value of i is first incremented which is an post increment so the further use of i will take i value to 3 and in the if block continue statement is there which again restart the loop fron top then due to loop increment value of i = 4 so when it goes in else if block value of i will be 5*4 = 20 which make else if condition true and due to use of break statement it break down the loop interation thus the output is 05
2nd Feb 2020, 4:43 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 2
Hi. You need to figure out which "if" triggers for every possible "i". When i=0 1st if - false 2nd if - false so triggers "else": cout<<5*i; When i=1 The same as before: cout<<5*i; When i=2 1st if - true so it triggers: i++; continue; When i=4 (not 3 because of i++ in if and i++ in loop) 1st if - false 2nd if - true so 2nd if triggers: break;
2nd Feb 2020, 4:42 AM
Stephan
Stephan - avatar
+ 2
I hope you know how a for loop works- So there are 2 conditions. 1) if i==2 // then i++ and continue. 2) if 5*i == 20 // it's possible when i=4. And break out of the loop. 3) and for rest of the 'i' values print 5*i. Loop start- i=0, i<8 true // else is executed and 5*0 = 0 i=1, i<8 true // else is executed and 5*1 = 5 i=2, i<8 true // if is executed and i++ increments i value by 1, so i is 3 and continue starts the next loop. Since i is already 3 now in for loop i++ will make i=4. i=4, i<8 true // else if is executed since 5*4 = 20. The break statement terminates the loop and program execution stops. Final output should be- 05
2nd Feb 2020, 4:48 AM
Avinesh
Avinesh - avatar