+ 4

Please explain how this works?

int x=0; for(int i=1 ; i<4; i++) { x+=i; } cout << x << endl; //output 6

12th Jun 2017, 3:25 AM
primex
primex - avatar
5 Respostas
+ 14
Iteration 1 : i = 1; x += 1 => x = 0 + 1 = 1; Iteration 2 : i = 2; x += 2 => x = 1 + 2 = 3; Iteration 3 : i = 3; x += 3 => x = 3 + 3 = 6; i becomes 4 and loop condition (i < 4) fails.
12th Jun 2017, 3:33 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 7
@Krishna thank u 😊
12th Jun 2017, 3:36 AM
primex
primex - avatar
+ 4
@Paavan. thank you. yeah. I got it 😊
12th Jun 2017, 6:39 AM
primex
primex - avatar
+ 3
first you have declared an integer variable x = 0. then you have declared a for loop where the condition is that if i=1 then i<4.i++. here the compiler will run this loop upto when the i is smaller then 4 , as soon as i becomes 4 then it's not smaller then 4, it's equal to 4, so the loop will break executing. Here the i++ means that only that upto the condition becomes false, execute the loop continuously and everytime the loop will execute it will add 1 to x itself. and after the execution of loop gets completed then it will print the x. i think you may have understood.
12th Jun 2017, 6:31 AM
Paavan Gupta
Paavan Gupta - avatar
+ 3
welcome☺👍
12th Jun 2017, 8:08 AM
Paavan Gupta
Paavan Gupta - avatar