编写一个 C++ 程序,使用 for 循环打印带对角线的空心正方形星形图案。
#include<iostream>
using namespace std;
int main()
{
int i, j, side;
cout << "Enter Side of a Hollow Square with Diagonals = ";
cin >> side;
cout << "Hollow Square Star With Diagonals Pattern\n";
for(i = 1; i <= side; i++)
{
for(j = 1; j <= side; j++)
{
if (i == 1 || i == side || i == j ||
j == 1 || j == side || j == side - i + 1)
{
cout << "* ";
}
else {
cout << " ";
}
}
cout << "\n";
}
return 0;
}

此 C++ 示例 使用 while 循环打印给定字符的带对角线的空心正方形图案。
#include<iostream>
using namespace std;
int main()
{
int i, j, side;
char ch;
cout << "Enter Side of a Hollow Square with Diagonals = ";
cin >> side;
cout << "Enter Symbol for Hollow Square with Diagonals = ";
cin >> ch;
cout << "Hollow Square With Diagonals Pattern\n";
for(i = 1; i <= side; i++)
{
for(j = 1; j <= side; j++)
{
if (i == 1 || i == side || i == j ||
j == 1 || j == side || j == side - i + 1)
{
cout << ch << " ";
}
else {
cout << " ";
}
}
cout << "\n";
}
return 0;
}
Enter Side of a Hollow Square with Diagonals = 16
Enter Symbol for Hollow Square with Diagonals = #
Hollow Square With Diagonals Pattern
# # # # # # # # # # # # # # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # # # # # # # # # # # # # #