编写一个 C++ 程序来打印矩形星形图案,并附带一个示例。在此 C++ 矩形星形图案中,我们在 for 循环中使用了 if 语句。它有助于为矩形边框打印给定的字符或 '*',为所有剩余位置打印空格。我们可以称之为“空心”矩形星形。
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns;
char ch;
cout << "\nPlease Enter the Total Number of Rectangle Rows = ";
cin >> rows;
cout << "\nPlease Enter the Total Number of Rectangle Columns = ";
cin >> columns;
cout << "\nPlease Enter Any Symbol to Print = ";
cin >> ch;
cout << "\n-----Rectangle Pattern-----\n";
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
cout << ch;
}
else
{
cout << " ";
}
}
cout << "\n";
}
return 0;
}

C++ 打印矩形星形图案示例 2
在此 C++ 示例中,我们删除了 If 语句,以打印一个完整的星形矩形。
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns;
char ch;
cout << "\nPlease Enter the Total Number of Rectangle Rows = ";
cin >> rows;
cout << "\nPlease Enter the Total Number of Rectangle Columns = ";
cin >> columns;
cout << "\nPlease Enter Any Symbol to Print = ";
cin >> ch;
cout << "\n-----Rectangle Pattern-----\n";
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
cout << ch;
}
cout << "\n";
}
return 0;
}
Please Enter the Total Number of Rectangle Rows = 8
Please Enter the Total Number of Rectangle Columns = 20
Please Enter Any Symbol to Print = $
-----Rectangle Pattern-----
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
使用 While 循环的 C++ 打印矩形星形图案程序
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns;
char ch;
cout << "\nPlease Enter the Total Number of Rectangle Rows = ";
cin >> rows;
cout << "\nPlease Enter the Total Number of Rectangle Columns = ";
cin >> columns;
cout << "\nPlease Enter Any Symbol to Print = ";
cin >> ch;
cout << "\n-----Rectangle Pattern-----\n";
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
cout << ch;
j++;
}
cout << "\n";
i++;
}
return 0;
}
Please Enter the Total Number of Rectangle Rows = 10
Please Enter the Total Number of Rectangle Columns = 22
Please Enter Any Symbol to Print = @
-----Rectangle Pattern-----
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@