View Full Version : Can someone explain why this isn't an infinite loop? (C++)
This was a question from my C++ midterm.
I see an infinite loop, but the correct answer is 12. Can anyone explain this?
Question: What is the value of i after the loop exits?
int i;
for(i=0; i < 10; i++)
i+=3;
i=1;
DaleSwanson
Dec12-11, 08:17 PM
Think like a compiler; ignore white space; treat semicolons as ends of lines.
jhae2.718
Dec12-11, 08:37 PM
I'm assuming that should be:
int i;
for(i=0; i < 10; i++)
i+=3;
i+=1;
as otherwise the answer would be 1.
The best way is to step through the code by hand:
Iteration Value i<10?
1 3 yes // starts at zero then adds 3
2 7 yes // incremented by 1, then add 3
3 11 no // same, then stops at next test
then add one to get 12.
dimensionless
Dec12-11, 08:56 PM
The loop ends when i = 10 or i > 10. This condition is set in the line:
for(i=0; i < 10; i++)
Without any braces, the for loop only includes the next statement. The equivalent code with braces would be:
int i;
for(i=0; i < 10; i++)
{
i+=3;
}
i=1;
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.