Can someone explain why this isn't an infinite loop? (C++)

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
PNGeng
Messages
17
Reaction score
0
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?
Code:
int i;
for(i=0; i < 10; i++)
i+=3;
i=1;
 
Physics news on Phys.org
Think like a compiler; ignore white space; treat semicolons as ends of lines.
 
I'm assuming that should be:
Code:
int i;
for(i=0; i < 10; i++)
i+=3;
i[b]+=[/b]1;
as otherwise the answer would be 1.

The best way is to step through the code by hand:
Code:
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.
 
Last edited:
The loop ends when i = 10 or i > 10. This condition is set in the line:
Code:
for(i=0; i < 10; i++)
 
Without any braces, the for loop only includes the next statement. The equivalent code with braces would be:

Code:
int i;

    for(i=0; i < 10; i++)
    {
        i+=3;
    }

    i=1;