使用嵌套for循环和if语句在c ++中编码空心方块

时间:2015-02-06 00:22:01

标签: c++

因此,对于实验室项目,目标是使用" *。"打印出形状。 四个基本形状是正方形,两个向下指向右三角形和一个空心方形。对于我输入的任何整数,一切似乎都能正常工作但是我并不完全确定我正确地为空心方块做了循环,并且如果有人能给我一些建议,我希望它。

#include <iostream>

using std::cout; using std::endl; using std::cin;

int main()
{
    cout << "Input arbitrary integer ";
    int n;
    cin >> n;
    cout << endl;

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++)
        {
            cout << "*";
        }
        cout << endl;
    }
    cout << endl;

    for (int i = 1; i <= n; i++){
        for (int j = n; j >= i; j--)
        {
            cout << "*";
        }
        cout << endl;
    }
    cout << endl;

    for (int i = 1; i <= n; i++){
        for (int j = 2; j <= i; j++)
        {
            cout << " ";
        }
        for (int j = n; j >= i; j--)
        {
            cout << "*";
        }
        cout << endl;
    }
    cout << endl;

    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++)
        {
            if (i == 1)
                cout << "*";
            else if (j == 1)
                cout << "*";
            else if (i == n)
                cout << "*";
            else if (j == n)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

}

0 个答案:

没有答案