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

Click For Summary
The discussion revolves around a C++ midterm question regarding the value of the variable 'i' after a specific loop execution. The loop increments 'i' by 3 in each iteration, but there is confusion about the final value due to the placement of the statements. The correct interpretation shows that the loop runs until 'i' reaches 10, resulting in 'i' being 12 after the loop exits. The loop's behavior is clarified by stepping through the iterations manually, demonstrating that 'i' starts at 0, increments to 3, then 7, and finally 11 before the loop condition fails. The final increment outside the loop sets 'i' to 12. The importance of understanding loop structure without braces is emphasized, as it affects the scope of the loop's execution.
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;
 
Technology 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;
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 36 ·
2
Replies
36
Views
917
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
Replies
18
Views
3K
  • · Replies 17 ·
Replies
17
Views
3K
Replies
1
Views
2K
  • · Replies 16 ·
Replies
16
Views
3K
  • · Replies 29 ·
Replies
29
Views
10K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K