开发者

drawing a simple triangle with a while loop

开发者 https://www.devze.com 2023-01-16 23:19 出处:网络
Back learning after silly life issues derailed me! I decided to switch my learning material and I\'m now working through Accelerated C++.

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 bu开发者_高级运维t 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.


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.


I'm the author of the exercise solution that the OP showed above. I apologize for the confusion; I'll make a note to go back and add some comments to the solutions, which are at http://www.parkscomputing.com/accelerated-cpp-solutions/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号