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

188 阅读1分钟

编写一个C++程序,使用for循环打印除对角线数字模式外的所有零的正方形。

#include using namespace std;

int main() { int rows;


cout << "Enter Square with Diagonal Numbers Side = ";
cin >> rows;

cout << "Square with Numbers in Diaginal and Remaining 0's\\n";

for (int i = 1; i <= rows; i++)
{
	for (int j = 1; j < i; j++)
	{
		cout << "0 ";
	}
	cout << i << " ";

	for (int k = i; k < rows; k++)
	{
		cout << "0 ";
	}
	cout << "\\n";
}

image.png

这是在C++中打印带有对角线数字和所有剩余项目零的正方形图案的另一种方法。

#include using namespace std;

int main() { int rows;


cout << "Enter Square with Diagonal Numbers Side = ";
cin >> rows;

cout << "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)
		{
			cout << i << " ";
		}
		else
		{
			cout << "0 ";
		}
	}
	cout << "\\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 

使用while循环打印带有对角线数字图案的正方形的C++程序

#include using namespace std;

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

cout << "Enter Square with Diagonal Numbers Side = ";
cin >> rows;

cout << "Square with Numbers in Diaginal and Remaining 0's\\n";
i = 1;

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

	while (j <= rows)
	{
		if (i == j)
		{
			cout << i << " ";
		}
		else
		{
			cout << "0 ";
		}
		j++;
	}
	cout << "\\n";
	i++;
}

}

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 

这个C++程序使用do while循环显示对角线数字递增的正方形图案,所有剩余的1都是0。


#include using namespace std;

int main() { int rows;

cout << "Enter Square with Diagonal Numbers Side = ";
cin >> rows;

cout << "Square with Numbers in Diaginal and Remaining 0's\\n";
int i = 1;

do
{
	int j = 1;

	do
	{
		if (i == j)
		{
			cout << i << " ";
		}
		else
		{
			cout << "0 ";
		}

	} while (++j <= rows);

	cout << "\\n";

} while (++i <= rows);
Enter Square with Diagonal Numbers Side = 14
Square with Numbers in Diaginal and Remaining 0's
1 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 3 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 5 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 7 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 9 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 11 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 13 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 14