C++ Program to Print Simple Full Pyramid Pattern

24/04/2024 0 By indiafreenotes

Printing a full pyramid pattern using C++ involves using nested loops to properly align stars (or any other characters) in a symmetrical pyramid shape. A full pyramid pattern is centered, and each row contains an increasing number of stars based on the row number.

Here’s a C++ program that demonstrates how to print a simple full pyramid pattern:

#include <iostream>

using namespace std;

int main() {

    int rows;

    cout << “Enter the number of rows for the pyramid: “;

    cin >> rows;

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

        // Print spaces for alignment to the center

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

            cout << ” “;

        }

        // Print stars: there are 2*i – 1 stars in the ith row

        for (int star = 1; star <= 2 * i – 1; star++) {

            cout << “*”;

        }

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

    }

    return 0;

}

Explanation of the Program:

  • User Input for Rows:

The user is prompted to enter the number of rows (rows) for the pyramid. This number determines the height of the pyramid.

  • Outer Loop for Rows:

This loop iterates from 1 up to rows. Each iteration of this loop represents one row of the pyramid.

  • Inner Loop for Printing Spaces:

Before printing any stars, this loop prints spaces to ensure that the pyramid is centered. The number of spaces decreases as the row number increases. For each row i, it prints rows – i spaces.

  • Inner Loop for Printing Stars:

This loop prints the stars needed for each row. In the ith row, there are 2*i – 1 stars. This ensures that the pyramid has a symmetrical appearance with a wider base and a single star at the top.

  • Line Break After Each Row:

After printing the required number of stars, a newline (endl) is used to move to the next line, ensuring that each level of the pyramid starts on a new line.