介绍
在本实验中,你将学习如何使用 C++ 编程语言创建一个由星号(*)组成的半金字塔图案。本实验将教你如何使用迭代实现各种嵌套循环结构。
在本实验中,你将学习如何使用 C++ 编程语言创建一个由星号(*)组成的半金字塔图案。本实验将教你如何使用迭代实现各种嵌套循环结构。
~/project
目录中创建一个新文件首先,在终端中使用 touch
命令在 ~/project
目录中创建一个名为 half_pyramid_star.cpp
的新文件:
touch ~/project/half_pyramid_star.cpp
现在,在文本编辑器或 IDE 中打开 half_pyramid_star.cpp
文件,并将以下代码复制到其中:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << "===== Program to print a Half Pyramid using * =====\n\n\n";
int i, j, rows;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
//outer loop moves to a specific row
for (i = 1; i <= rows; i++)
{
//inner loop determines the amount of "*" printed in the row
for (j = 1; j <= i; j++)
{
cout << "* ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
上述代码会提示用户输入要打印的半金字塔图案的行数,并使用两个嵌套循环在每一行打印“*”。
在终端窗口中输入以下命令以编译 half_pyramid_star.cpp
代码:
g++ ~/project/half_pyramid_star.cpp -o ~/project/half_pyramid_star && ~/project/half_pyramid_star
上述命令将编译代码,生成一个名为 half_pyramid_star
的可执行文件,并运行该程序。
在本实验中,你学习了如何使用 C++ 编程语言创建一个由星号(*)组成的半金字塔图案。通过利用嵌套循环并理解其作用范围,你成功完成了实验。本实验是理解嵌套循环结构和迭代的基础步骤,这将有助于解决问题或创建复杂的形状。