C++ Program to Print Right Half Pyramid Pattern

22/04/2024 0 By indiafreenotes

To print a right half pyramid pattern in C++, you can utilize nested loops. This kind of pattern is characterized by stars (*) that form a right-angled triangle with the right angle on the left side. The number of stars on each line corresponds to the line number, starting with one star on the first line and increasing by one star per line.

Here is a simple C++ program that prompts the user to enter the number of rows for the pyramid and then prints the corresponding right half pyramid pattern:

#include <iostream>

using namespace std;

int main() {

    int rows;

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

    cin >> rows;

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

        // Print leading spaces to shift the stars to the right

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

            cout << ”  “;

        }

        // Print stars: number of stars on each row equals the row number

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

            cout << “* “;

        }

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

    }

    return 0;

}

 

Breakdown of the Program:

  1. User Input for Rows:

The program first asks the user to specify the number of rows for the pyramid.

  1. Outer Loop:

This loop iterates from 1 to the number of rows (rows). Each iteration represents a row in the pyramid.

  1. Inner Loop for Spaces:

Before printing stars, this loop prints spaces. The number of spaces decreases as the row number increases. This alignment creates the right shift of the pyramid, maintaining the right half appearance.

  1. Inner Loop for Stars:

This loop prints stars (*). The number of stars printed is equal to the current row number (i). This means the first row will have one star, the second row two stars, and so forth.

  1. Newline After Each Row:

A newline character (endl) is used after each row to ensure that each level of the pyramid starts on a new line.