C 语言打印带对角线数字的方形图案程序

编写一个C语言程序来打印带对角线数字的方形图案。或者用C语言程序使用for循环打印除了对角线数字图案和其余所有零之外的方形。

#include <stdio.h>

int main()
{
	int rows;

	printf("Enter Square with Diagonal Numbers Side = ");
	scanf("%d", &rows);

	printf("Square with Numbers in Diaginal and Remaining 0's\n");

	for (int i = 1; i <= rows; i++)
	{
		for (int j = 1; j < i; j++)
		{
			printf("0 ");
		}
		printf("%d ", i);

		for (int k = i; k < rows; k++)
		{
			printf("0 ");
		}
		printf("\n");
	}
}
C Program to Print Square With Diagonal Numbers Pattern

这是在C语言中打印带对角线数字且其余为零的方形图案的另一种方法。

#include <stdio.h>

int main()
{
	int rows;

	printf("Enter Square with Diagonal Numbers Side = ");
	scanf("%d", &rows);

	printf("Square with Numbers in Diaginal and Remaining 0's\n");

	for (int i = 1; i <= rows; i++)
	{
		for (int j = 1; j <= rows; j++)
		{
			if (i == j)
			{
				printf("%d ", i);
			}
			else
			{
				printf("0 ");
			}
		}
		printf("\n");
	}
}
Enter Square with Diagonal Numbers Side = 9
Square with Numbers in Diaginal and Remaining 0's
1 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 0 
0 0 0 4 0 0 0 0 0 
0 0 0 0 5 0 0 0 0 
0 0 0 0 0 6 0 0 0 
0 0 0 0 0 0 7 0 0 
0 0 0 0 0 0 0 8 0 
0 0 0 0 0 0 0 0 9 

此C语言程序显示递增对角线数字的方形图案。使用while循环,其余所有都是零。

#include <stdio.h>

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

	printf("Enter Square with Diagonal Numbers Side = ");
	scanf("%d", &rows);

	printf("Square with Numbers in Diaginal and Remaining 0's\n");
	i = 1;

	while (i <= rows)
	{
		j = 1;

		while (j <= rows)
		{
			if (i == j)
			{
				printf("%d ", i);
			}
			else
			{
				printf("0 ");
			}
			j++;
		}
		printf("\n");
		i++;
	}
}
Enter Square with Diagonal Numbers Side = 15
Square with Numbers in Diaginal and Remaining 0's
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 10 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 11 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 12 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 13 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 14 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 

这个C语言示例使用do-while循环打印方形数字图案,其对角线是连续数字,其余均为零。

#include <stdio.h>

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

	printf("Enter Square with Diagonal Numbers Side = ");
	scanf("%d", &rows);

	printf("Square with Numbers in Diaginal and Remaining 0's\n");
	i = 1;

	do
	{
		j = 1;

		do
		{
			if (i == j)
			{
				printf("%d ", i);
			}
			else
			{
				printf("0 ");
			}

		} while (++j <= rows);

		printf("\n");

	} while (++i <= rows);
}
Enter Square with Diagonal Numbers Side = 12
Square with Numbers in Diaginal and Remaining 0's
1 0 0 0 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 0 0 0 0 
0 0 0 4 0 0 0 0 0 0 0 0 
0 0 0 0 5 0 0 0 0 0 0 0 
0 0 0 0 0 6 0 0 0 0 0 0 
0 0 0 0 0 0 7 0 0 0 0 0 
0 0 0 0 0 0 0 8 0 0 0 0 
0 0 0 0 0 0 0 0 9 0 0 0 
0 0 0 0 0 0 0 0 0 10 0 0 
0 0 0 0 0 0 0 0 0 0 11 0 
0 0 0 0 0 0 0 0 0 0 0 12