はじめに
この実験では、C++ プログラミング言語を使って、数字を使って逆半ピラミッド構造を表示する方法を学びます。パターンを反復して表示するために、ネストされたループ構造を使います。
ファイルを作成して開く
ターミナルに移動し、次のコマンドを使って ~/project ディレクトリに新しいファイル main.cpp を作成します。
touch ~/project/main.cpp
ファイルを作成した後、テキストエディタを使って開きます。
初期コードを書く
main.cpp ファイルに次のコードを追加します。
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to print a Reverse Half Pyramid using Numbers ===== \n\n";
//i は外側のループを反復するために、j は内側のループのために使用されます
int i, j, rows;
//各行の数字の範囲を表すために使用されます
int last;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";
//外側のループは特定の行に移動するために使用されます
for (i = 1; i <= rows; i++)
{
//外側のループが行番号を維持することを表示するために使用されます
cout << "Row ## " << i << " contains numbers from 1 to " << (rows - i + 1) << " : ";
last = rows -i + 1;
//内側のループは特定の行における * の数を決定するために使用されます
for (j = 1; j<= last; j++)
{
cout << j << " ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
コードをコンパイルして実行する
次のコマンドを使ってコードをコンパイルして実行します。
g++ main.cpp -o main
./main
次の出力が表示されます。
Welcome to LabEx :-)
===== Program to print a Reverse Half Pyramid using Numbers =====
Enter the number of rows in the pyramid: 6
The required Reverse Pyramid pattern containing 6 rows is:
Row ## 1 contains numbers from 1 to 6 : 1 2 3 4 5 6
Row ## 2 contains numbers from 1 to 5 : 1 2 3 4 5
Row ## 3 contains numbers from 1 to 4 : 1 2 3 4
Row ## 4 contains numbers from 1 to 3 : 1 2 3
Row ## 5 contains numbers from 1 to 2 : 1 2
Row ## 6 contains numbers from 1 to 1 : 1
まとめ
この実験では、C++ プログラミング言語を使って、ネストされたループを使って数字で逆半ピラミッド構造を表示する方法を学びました。



