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

C++ 程序使用 while 循环打印 V 星形图案
#include<iostream>
using namespace std;
int main()
{
int i, j, k, l, rows;
cout << "Enter V Shape Star Pattern Rows = ";
cin >> rows;
cout << "Printing V Shape Star Pattern\n";
i = 1;
while (i <= rows)
{
j = 1;
while (j <= i)
{
cout << "*";
j++;
}
k = 1;
while (k <= 2 * (rows - i))
{
cout << " ";
k++;
}
l = 1;
while (l <= i)
{
cout << "*";
l++;
}
cout << "\n";
i++;
}
}
Enter V Shape Star Pattern Rows = 10
Printing V Shape Star Pattern
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
******** ********
********* *********
********************
此程序使用 do while 循环打印星形的字母 V 图案。
#include<iostream>
using namespace std;
int main()
{
int i, j, k, l, rows;
cout << "Enter V Shape Star Pattern Rows = ";
cin >> rows;
cout << "Printing V Shape Star Pattern\n";
i = 1;
do
{
j = 1;
do
{
cout << "*";
} while (++j <= i);
k = 1;
while (k <= 2 * (rows - i))
{
cout << " ";
k++;
}
l = 1;
do
{
cout << "*";
} while (++l <= i);
cout << "\n";
} while (++i <= rows);
}
Enter V Shape Star Pattern Rows = 13
Printing V Shape Star Pattern
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
******** ********
********* *********
********** **********
*********** ***********
************ ************
**************************
在此示例中,vStarPattern 函数允许输入任何字符,并打印给定字符的 V 图案。
#include<iostream>
using namespace std;
void VShapePattern(int rows, char ch)
{
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
cout << ch;
}
for (int k = 1; k <= 2 * (rows - i); k++)
{
cout << " ";
}
for (int l = 1; l <= i; l++)
{
cout << ch;
}
cout << "\n";
}
}
int main()
{
int rows;
char ch;
cout << "Enter Character for V Pattern = ";
cin >> ch;
cout << "Enter Rows = ";
cin >> rows;
cout << "Printing V Shape Pattern\n";
VShapePattern(rows, ch);
}
Enter Character for V Pattern = #
Enter Rows = 17
Printing V Shape Pattern
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
######### #########
########## ##########
########### ###########
############ ############
############# #############
############## ##############
############### ###############
################ ################
##################################