C语言打印X形数字图案程序

在本文中,我们将展示如何使用for循环、while循环和函数编写一个C程序来打印X形数字图案。下面的示例允许用户输入总行数,嵌套的for循环将它们从开始迭代到结束。接下来,程序将以X形打印数字图案。

#include <stdio.h>

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

printf("Enter Rows = ");
scanf("%d",&rows);

for (i = 0 ; i < rows; i++ )
{
for (j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%d ", j + 1);
}
else
{
printf(" ");
}
}
printf("\n");
}

return 0;
}
Enter Rows = 12
1           12 
 2         11  
  3       10   
   4     9    
    5   8     
     6 7      
     6 7      
    5   8     
   4     9    
  3       10   
 2         11  
1           12 

该程序使用while循环来迭代X形图案的行和列,并在图案的每一行中打印数字,而不是使用for循环。要获取更多数字程序,请点击这里

#include <stdio.h>

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

printf("Enter Rows = ");
scanf("%d",&rows);

i = 0;
while (i < rows )
{
j = 0;
while (j < rows )
{
if (i == j || j == rows - 1 - i)
{
printf("%d", j + 1);
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}

return 0;
}
Enter Rows = 15
1             15
 2           14 
  3         13  
   4       12   
    5     11    
     6   10     
      7 9      
       8       
      7 9      
     6   10     
    5     11    
   4       12   
  3         13  
 2           14 
1             15

在此C程序中,我们创建了一个NumbersinXShape函数,该函数接受用户输入的行数,并以字母X的形状打印数字图案。

#include <stdio.h>

void NumbersinXShape(int rows)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
printf("%d ", j + 1);
}
else
{
printf(" ");
}
}
printf("\n");
}
}

int main()
{
int rows;

printf("Enter Rows = ");
scanf("%d",&rows);

NumbersinXShape(rows);
return 0;
}
C Program to Print X Pattern of Numbers