views:

100

answers:

1

Back learning after silly life issues derailed me! I decided to switch my learning material and I'm now working through Accelerated C++.

Chapter 2, Exercise 5:
Write a set of "*" characters so that they form a square, a rectangle, and a triangle.

I tried but just couldn't get the triangle down exactly. A quick google found the following answer:

// draw triangle
    int row = 0;
    int col = 0;
    int height = 5;

// draw rows above base
    while (row < height - 1)
    {
        col = 0;
        while (col < height + row)
        {
            ++col;
            if (col == height - row)
                cout << '*';
            else
            {
                if (col == height + row)
                    cout << '*';
                else
                    cout << ' ';
            }
        }
        cout << endl;
        ++row;
    }

// draw the base
    col = 0;

    while (col < height * 2 - 1)
    {
        cout << '*';
        ++col;
    }

I wanted to disect this and fully understand it as I had trouble coming up with my own answer. It doesn't matter how many times I go through it I cannot see how it's drawing the right side of the triangle:

- - - - *
- - - *
- - *
- *
*
* * * * * * * * * * 

That's what I get going through this loop on paper. Where on earth is that right side coming from? I have a gut feeling the expressions are doing something I'm not seeing. The code works.

+3  A: 

In the nested while loop, inside the else clause:

else
{
    if (col == height + row)
        cout << '*';  // This draws the right side
    else
        cout << ' ';
}

The trick is that the while loop doesn't quit until the column reaches height + row, which is the position of the right side. It prints the left side (at height - row) earlier, in the if clause that comes before this one.

Tim Yates
hmm, I'll try it again. I must be counting the iterations and variables wrong or something to that effect as I couldn't reach that part of the loop. I always broke out. Thanks.
aLostMonkey
Make sure you pay attention to `row` being incremented. In the first loop, `height - row == height + row`, so as soon as you reach the left side, the inner (but not outer) loop exits. On the second round, though, you will have two iterations between the left side and the right (when it exits), and so forth.
Tim Yates
If you can find one that works for you, it would also be a great idea to step through it using a debugger. Then you can be sure you're following the path that the computer takes. Something like `gdb` might be a bit tough to handle at this point though.
Tim Yates
I tried running a debugger via Code Blocks (my IDE of choice on windows). Couldn't get it going, but I didn't really put much effort into it. Thanks for the tip.
aLostMonkey
ok, I got Code Blocks going with gdb and I went through it step by step watching the variables change. Now it makes perfect sense. Many thanks!
aLostMonkey