+ 1

Simple code, output known, still confused.

int result = 0; for ( int i = 2; i < 5; i++ ) { result = result + i; } I know the output is 9, but I simply just cannot get my head around how it works, even though it's simple code. Please explain to this retard why the output is 9, thank you.

18th Jan 2018, 3:25 AM
Vexsf
Vexsf - avatar
4 odpowiedzi
+ 14
int result = 0; // set result as 0 for (int i = 2; i<5; i++){ //let i = 2; //Run the for loop till i is less than 5 means exit the loop when i == 5; //i++ add 1 to i when the loop runs but will return the previous value of i due to post-increment result = result + i; //assign result variable to itself + i // so /* //1st run result = 0 + 2 //now result is 2 //2nd run result = 2 + 3 //result is 5 //3rd run result = 5 + 4 //result is 9 // i == 5 now exit the loop */ }
18th Jan 2018, 3:40 AM
Lord Krishna
Lord Krishna - avatar
+ 9
put a couple of outputs in the loop. everything will become clear. I.e cout << result << " + " << i; result = result + i; cout << "=" << result << endl;
18th Jan 2018, 3:34 AM
jay
jay - avatar
+ 3
ty for the explanation Lord Krishna <3 easily understood. I feel smarter now for understanding it, but dumber for not seeing it first time. Love/hate rships tell me abt it
18th Jan 2018, 4:15 AM
Vexsf
Vexsf - avatar
+ 1
ty for the help jay :)
18th Jan 2018, 3:36 AM
Vexsf
Vexsf - avatar