C++ Program to Print Floyd’s pattern Triangle Pyramid

04/05/2024 0 By indiafreenotes

Floyd’s Triangle is a well-known pattern in the world of programming and mathematics. It is a triangular array of natural numbers, arranged in a staggered format where the rows increase in length incrementally. Each row contains consecutive numbers starting from 1.

In this C++ program, we will generate Floyd’s Triangle based on the number of rows specified by the user. The pattern involves filling the rows with increasing numbers, starting with 1 at the top.

C++ Code to Print Floyd’s Triangle:

#include <iostream>

using namespace std;

int main() {

    int rows, number = 1;

    // Prompting user to enter the number of rows

    cout << “Enter the number of rows for Floyd’s Triangle: “;

    cin >> rows;

    cout << “Floyd’s Triangle:” << endl;

    // Outer loop for handling the number of rows

    for (int i = 1; i <= rows; i++) {

        // Inner loop for handling the number of columns in each row

        for (int j = 1; j <= i; j++) {

            cout << number << ” “;

            number++;  // Increment number for next place

        }

        cout << endl; // Move to the next line after each row

    }

    return 0;

}

Explanation:

  1. Variables Declaration:

The variable rows stores the number of rows, and number keeps track of the current number to be printed, starting at 1.

  1. Input from User:

The user is asked to specify the number of rows they wish to generate in Floyd’s Triangle.

  1. Generating Floyd’s Triangle:

    • Outer Loop (i): Runs from 1 to rows, where i represents the current row number.
    • Inner Loop (j): Runs from 1 to i, reflecting that the number of elements in each row increases with the row number. Within this loop, the number is printed and then incremented.
    • Each row is printed on a new line (cout << endl).
  2. Output:

The triangle displays numbers in a staggered format, increasing with each row.

Example Output:

If the user enters 5 for the number of rows, the output will look like this:

Floyd’s Triangle:

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

This program clearly illustrates how nested loops can be used to manage and output data in specific formats, making it a good example for beginners learning about loops and sequence generation in C++.