Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Dec 12, 2011 #1
    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 (Text):
    int i;
    for(i=0; i < 10; i++)
    i+=3;
    i=1;

     
     
  2. jcsd
  3. Dec 12, 2011 #2
    Think like a compiler; ignore white space; treat semicolons as ends of lines.
     
  4. Dec 12, 2011 #3

    jhae2.718

    User Avatar
    Gold Member

    I'm assuming that should be:
    Code (Text):

    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 (Text):

    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: Dec 12, 2011
  5. Dec 12, 2011 #4
    The loop ends when i = 10 or i > 10. This condition is set in the line:
    Code (Text):

    for(i=0; i < 10; i++)
     
     
  6. Dec 12, 2011 #5

    rcgldr

    User Avatar
    Homework Helper

    Without any braces, the for loop only includes the next statement. The equivalent code with braces would be:

    Code (Text):

    int i;

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

        i=1;
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Can someone explain why this isn't an infinite loop? (C++)
  1. Infinite Loop (Replies: 0)

  2. Loop in c (Replies: 1)

Loading...