编写一个 C++ 程序,使用 for 循环打印沙漏星形图案。
#include<iostream>
using namespace std;
int main()
{
int i, j, k, rows;
cout << "Enter Sandglass Star Pattern Row = ";
cin >> rows;
cout << "Sandglass star Pattern\n";
for(i = 0; i <= rows - 1; i++)
{
for(j = 0; j < i; j++)
{
cout << " ";
}
for(k = i; k <= rows - 1; k++)
{
cout << "* ";
}
cout << "\n";
}
for(i = rows - 1; i >= 0; i--)
{
for(j = 0; j < i; j++)
{
cout << " ";
}
for(k = i; k <= rows - 1; k++)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}

此 C++ 示例 使用 while 循环打印给定字符的沙漏图案。
#include<iostream>
using namespace std;
int main()
{
int i = 0, j, k, rows;
char ch;
cout << "Enter Sandglass Star Pattern Row = ";
cin >> rows;
cout << "Enter Symbol to Print in Sandglass Pattern = ";
cin >> ch;
cout << "Sandglass Pattern of Given Symbol\n";
while(i <= rows - 1)
{
j = 0;
while( j < i)
{
cout << " ";
j++;
}
k = i;
while(k <= rows - 1)
{
cout << ch << " ";
k++;
}
cout << "\n";
i++;
}
i = rows - 1;
while( i >= 0)
{
j = 0;
while( j < i)
{
cout << " ";
j++;
}
k = i;
while(k <= rows - 1)
{
cout << ch << " ";
k++;
}
cout << "\n";
i--;
}
return 0;
}
Enter Sandglass Star Pattern Row = 12
Enter Symbol to Print in Sandglass Pattern = #
Sandglass Pattern of Given Symbol
# # # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # # # # # #
# # # # # # #
# # # # # #
# # # # #
# # # #
# # #
# #
#
#
# #
# # #
# # # #
# # # # #
# # # # # #
# # # # # # #
# # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # #