none
Understanding a code

    Question

  • I have a test in a few hours, I was doing my review and I have the following code:

    #include <iostream>
    using namespace std;

    int main()
    {
    int i = 4;
    while (i >= 1)
    {
    int j = 1;
    while (j >= 1)
    {
    cout << j;
    j = j - 1;
    }
    cout << i << endl;
    i = i - 1;
    }

    return 0;
    }

    it prints:

    14

    13

    12

    11

    But I don't understand why. Can someone help?

    Saturday, March 26, 2016 6:52 PM

Answers

  • Analyze this fragment of your code in isolation:

    int j = 1;
    while (j >= 1)
    {
       cout << j;
       j = j - 1;
    }

    It should be clear that this loop only executes once.  Because j is 1 at the beginning of the loop, and j is 0 after the loop, and therefore it prints a 1 (with no line ending).

    So the above fragment is as good as 

    cout << 1;

    int main()
    {
        int i = 4;
        while (i >= 1)
        {
            cout << 1; // Simplified.  See explanation above.
            cout << i << endl;
            i = i - 1;
        }
    
        return 0;
    }

    And hopefully you can see that this loop counts down with i initially at 4 and its last iteration is where i is 1.

    So it loops 4 times and the values of i are {4, 3, 2, 1}.

    So because it precedes writing i by writing a '1' with no line ending, it writes '1' '4'   then '1' '3', then '1' '2'  then '1'  '1', or simply:

    14
    13
    12
    11


    The no-line-ending part is perhaps the trick.  Or perhaps someone intended to initialize j = i; which would have produced a more interesting result because the inner loop wouldn't have simplified down to 1 iteration where the value of j is always the same.

    Sunday, March 27, 2016 2:54 AM