0

Could someone explain the code below and what the result would be

#include <iostream> using namespace std; int main() { int res = 0; int i = 1; for(;i<10;i+=3){ if(10/i==2) continue; res+=i; } cout<<res; return 0; }

11th Aug 2016, 6:15 PM
Michael Murandu
Michael Murandu - avatar
3 Answers
+ 3
As the increment in the for loop is 3 beggining in i=1 and ending at i<10... only three times the code in the for loop it's executed... first time i=1, second time i=4 and third time i=7.. the next iteration i equals 10 which don't satysfies the condition i<10... When the code inside the for loop it's executed.. only when i=4 is that 10/i equals 2 (remember that is a integer division and ignores decimals so 10/4 == 2)... only in the other two cases (i=1 and i =7) is the res+=i stament executed... beginning with res=0 you get: 1.- res+=1 -> res=0+1 -> res=1 2.- res+=7 -> res=1+7 -> res=8 After that.. it gets out of the for loop with res=8 and the cout << res it's executed... Hope it helped.
11th Aug 2016, 10:47 PM
Nelson Urbina
Nelson Urbina - avatar
0
8
11th Aug 2016, 7:26 PM
rahul sinha
0
l ran the code and it gave me 8 but l want to know how it gets to 8
11th Aug 2016, 9:09 PM
Michael Murandu
Michael Murandu - avatar