C 语言打印空心数字图案程序

如何编写 C 语言程序来打印空心数字图案?对于这个空心数字图案,我们将使用 For 循环和 While 循环。

C 语言打印空心数字图案示例程序

此 程序 允许用户输入行数和列数。这里,我们将打印一个由 1 组成的空心方框数字图案。我的意思是,它将打印第一行、最后一行、第一列和最后一列为 1,其余元素为空。

首先,我们使用 嵌套 for 循环 来迭代每一行和每一列的元素。接下来,我们在嵌套的 For 循环 中使用 If 语句 来检查它是否是第一行、第一列、最后一行或最后一列。

#include<stdio.h>

int main()
{
int i, j, rows, columns;

printf(" \nPlease Enter the Number of Rows : ");
scanf("%d", &rows);

printf(" \nPlease Enter the Number of Columns : ");
scanf("%d", &columns);

for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
printf("1");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
C program to Print Hollow Box Number Pattern 1

打印空心数字图案示例程序 2

这个空心方框数字程序 与第一个示例相同,但这次我们使用的是 While 循环 (只需将 C 语言 的 For 循环替换为 While 循环)。

#include<stdio.h>

int main()
{
int i, j, rows, columns;
i = 1;

printf(" \nPlease Enter the Number of Rows : ");
scanf("%d", &rows);

printf(" \nPlease Enter the Number of Columns : ");
scanf("%d", &columns);

while(i <= rows)
{
j = 1;
while(j <= columns)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
printf("1");
}
else
{
printf(" ");
}
j++;
}
i++;
printf("\n");
}
return 0;
}
Please Enter the Number of Rows : 10
 
Please Enter the Number of Columns : 22
1111111111111111111111
1                    1
1                    1
1                    1
1                    1
1                    1
1                    1
1                    1
1                    1
1111111111111111111111

打印空心数字图案示例程序 3

此 程序 与上面的示例相同,但我们更改了打印的数字。我的意思是,这个程序将打印由 0 组成的空心方框数字图案。因此,编译器将在第一行、最后一行、第一列和最后一列打印 0。

#include<stdio.h>

int main()
{
int i, j, rows, columns;

printf(" \nPlease Enter the Number of Rows : ");
scanf("%d", &rows);

printf(" \nPlease Enter the Number of Columns : ");
scanf("%d", &columns);

for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
printf("0");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Please Enter the Number of Rows : 12
 
Please Enter the Number of Columns : 24
000000000000000000000000
0                      0
0                      0
0                      0
0                      0
0                      0
0                      0
0                      0
0                      0
0                      0
0                      0
000000000000000000000000