9.打印正方形

76 阅读1分钟

题目描述

编写一个程序,模拟打印一个正方形的框。程序应该接受用户输入的正整数作为正方形的边长,并打印相应大小的正方形框。 请注意,内部为空白,外部是由 "*" 字符组成的框。

输入描述

输入只有一行,为正方形的边长 n

输出描述

输出正方形组成的框

输入示例

5

输出示例

*****
*   *
*   *
*   *
*****

题目分析

循环嵌套

1.一维数组遍历

image.png

for(int i = 0;i < n;i++){
    cout << arr[i] << " ";
}

2.二位数组遍历

image.png

二维数组通过两个索引来访问,a[0][0]表示1,也就是第一行第一列,a[1][2]表示8,也就是第二行第三列。这时候就需要for循环嵌套使用。

//外部循环行
for(int i = 0;i < 5; i++){
    //内部循环列
    for(int j = 0;j < 5; j++){
        cout << arr[i][j] << " ";
    }
    //每行结束后换行
    cout << endl;
}

代码编写

1.需要控制正方形的边长

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    return 0;
}

2.需要一个循环嵌套来控制打印

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

3.控制*的输出

image.png 如果在边界上,第一行,i==0;最后一行,i==n-1;第一列,j==0;最后一列,j==n-1;用||来组合,只要符合一个就输出*,否则打印空白

i == 0;//第一行
i == n-1;//最后一行
j == 0;//第一列
j == n-1;//最后一列


if(i==0||i==n-1||j==0||j==n-1){
    cout << "*";
}else{
    cout << " ";
}

4.完整代码

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    for(int i = 0;i < n; i++){
        for(int j = 0;j < n; j++){
            if(i==0||i==n-1||j==0||j==n-1){
                cout << "*";
            }else{
                cout << " ";
            }
        }
        cout << endl;
    }
    return 0;
}