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

  • C/++/#
  • Thread starter PNGeng
  • Start date
  • #1
17
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;
 

Answers and Replies

  • #2
352
2
Think like a compiler; ignore white space; treat semicolons as ends of lines.
 
  • #3
jhae2.718
Gold Member
1,161
20
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:
  • #4
The loop ends when i = 10 or i > 10. This condition is set in the line:
Code:
for(i=0; i < 10; i++)
 
  • #5
rcgldr
Homework Helper
8,707
534
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;
 

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

Replies
13
Views
1K
Replies
3
Views
595
Replies
2
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
585
Replies
29
Views
6K
Replies
2
Views
902
  • Last Post
Replies
10
Views
1K
Replies
25
Views
1K
Top