C++ 修正フロイズ三角形プログラム

皆さんこんにちは!

このチュートリアルでは、修正フロイド三角形を印刷する方法を学びます。 、C++ プログラミング言語で。

フロイドの三角形とは?

フロイドの三角形は、自然数の直角三角形配列です。これは、左上隅の 1 から始まる連続した数字で三角形の行を埋めることによって定義されます。

Modified Floyd's Triangle では、各行は行番号で始まり、すべての連続番号を出力し、no を含みます。行番号に等しい列の数 .以下のコードと出力スニペットは、前述の定義を理解するのに役立ちます。

* を使用するすべてのパターン または アルファベット または数字 ネストされたループ構造を利用することで達成されます どのように反復するか、どこまで反復するかを知ることによって.

このセクションで取り上げるすべてのパターンは、この概念を理解し、独自のパターンを形成しながらよりよく視覚化するのに役立つと信じています。このような質問は、さまざまなインタビューでわずかな変更を加えて非常に頻繁に尋ねられるためです.

コード:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to print Floyd's Triangle ===== \n\n";

    //i to iterate the outer loop and j for the inner loop
    int i, j, rows;

    //to denote the range of numbers in each row
    int n=0, first,last; 

    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;

    cout << "\n\nThe required Floyd's Triangle containing " << rows << " rows is:\n\n";

    //outer loop is used to move to a particular row
    for (i = 1; i <= rows; i++)
    {

        first = i;
        last  = first + i -1;
       
        //to display that the outer loop maintains the row number
        //cout << "Row # " << i << " contains the numbers from " << first << " to " << last << " :    ";

        
        //inner loop is used to decide the number of columns in a particular row
          for (j = 1; j <= i; ++j) // remember: in such cases, ++j works same as j++ (but not always- we will cover this in upcoming posts)
            cout << n + j << " ";

        n++;
        cout << endl; //endl works same as '\n'
    }

    cout << "\n\n";

    return 0;
}

// を削除するだけで、各行の数値の範囲に関する詳細情報を取得できます。 以下に示すコード行のコメントを外します .

//cout << "Row # " << i << " contains the numbers from " << first << " to " << last << " :    ";

出力 1 :提供されたコードをそのまま実行すると、

出力 2 :範囲を出力する行のコメントを外すと、

最初に、このようなパターンを紙に 1 行ずつ描くことを強くお勧めします ネストされた構造をよりよく理解するのに役立つため、プログラミングに入る前に。

学び続ける :)