C++ でアスタリスクを使った逆半ピラミッドパターン

C++C++Beginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C++ プログラムを書いてアスタリスク (*) を使って逆半ピラミッドパターンを出力する方法を学びます。* やアルファベット、数字を使ったこのようなパターンは、どこまで繰り返すかを知り、ネストされたループ構造を使うことで実現できます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/ControlFlowGroup -.-> cpp/for_loop("For Loop") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/for_loop -.-> lab-96220{{"C++ でアスタリスクを使った逆半ピラミッドパターン"}} cpp/output -.-> lab-96220{{"C++ でアスタリスクを使った逆半ピラミッドパターン"}} cpp/user_input -.-> lab-96220{{"C++ でアスタリスクを使った逆半ピラミッドパターン"}} cpp/files -.-> lab-96220{{"C++ でアスタリスクを使った逆半ピラミッドパターン"}} cpp/code_formatting -.-> lab-96220{{"C++ でアスタリスクを使った逆半ピラミッドパターン"}} end

プロジェクトのセットアップ

ターミナルを開き、~/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++ を使ってアスタリスクで逆半ピラミッドパターンを出力する実験を成功裏に完了しました。

ネストされたループ構造は、このようなパターンを作成するのに非常に役立ちます。ループがどのように動作するか、そしてより複雑なパターンを構築するためにどのようにループを繰り返すかを理解することは重要です。