+ 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.
4 Answers
+ 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
*/
}
+ 9
put a couple of outputs in the loop. everything will become clear.
I.e
cout << result << " + " << i;
result = result + i;
cout << "=" << result << endl;
+ 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
+ 1
ty for the help jay :)