はじめに
この実験では、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++ を使ってアスタリスクで逆半ピラミッドパターンを出力する実験を成功裏に完了しました。
ネストされたループ構造は、このようなパターンを作成するのに非常に役立ちます。ループがどのように動作するか、そしてより複雑なパターンを構築するためにどのようにループを繰り返すかを理解することは重要です。



