介绍
在本实验中,你将学习如何通过编写 C++ 程序来打印一个由星号(*)组成的反向半金字塔图案。所有使用 *、字母或数字的此类图案都是通过利用嵌套循环结构来实现的,关键在于了解如何迭代以及迭代到哪里。
在本实验中,你将学习如何通过编写 C++ 程序来打印一个由星号(*)组成的反向半金字塔图案。所有使用 *、字母或数字的此类图案都是通过利用嵌套循环结构来实现的,关键在于了解如何迭代以及迭代到哪里。
打开终端,在 ~/project
目录下创建一个名为 pyramid.cpp
的 C++ 源文件:
cd ~/project
touch pyramid.cpp
使用文本编辑器打开该文件。
将以下代码添加到 pyramid.cpp
文件中。
//Cpp Reverse Half Pyramid Pattern Using Asterix
//Nested Loop Structure
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to print a Reverse Half Pyramid using * ===== \n\n";
//i to iterate the outer loop and j for the inner loop
int i, j, rows;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";
//outer loop is used to move to a particular row
for (i = 1; i <= rows; i++)
{
//to display that the outer loop maintains the row number
cout << "Row ## " << i << " contains " << (rows - i + 1) << " stars : ";
//inner loop is used to decide the number of * in a particular row
for (j = rows; j >= i; j--)
{
cout << "* ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
该程序接收用户输入的行数 rows
,并使用 *
显示用户输入行数的反向半金字塔图案。
保存对 pyramid.cpp
文件的更改并退出文本编辑器。在终端中使用以下命令编译代码:
g++ pyramid.cpp -o pyramid
在终端中输入以下命令以执行编译后的程序:
./pyramid
输入金字塔的行数,程序将输出包含指定行数的反向半金字塔图案。
恭喜!你已经成功完成了使用 C++ 打印星号反向半金字塔图案的实验。
嵌套循环结构对于创建此类图案非常有用。理解循环的工作原理以及如何通过它们进行迭代,对于构建更复杂的图案非常重要。