C++ Program to Print Left Half Pyramid Pattern

23/04/2024 0 By indiafreenotes

Creating a left half pyramid pattern in C++ involves using nested loops to align a series of asterisks (*) into a pyramid shape, aligning the right side of the pyramid against the left margin of your output console. This pattern is easier to generate because it does not require additional spaces for alignment, unlike the right half pyramid.

Here’s how you can write a C++ program to print a left half pyramid pattern:

#include <iostream>

using namespace std;

int main() {

    int rows;

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

    cin >> rows;

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

        // 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;

}

 

Explanation of the Program:

  1. User Input for Rows:

The program prompts the user to enter the number of rows for the pyramid. This value dictates how tall the pyramid will be.

  1. Outer Loop:

This loop runs from 1 to the entered number of rows. Each iteration of this loop represents a single row of the pyramid.

  1. Inner Loop for Printing Stars:

Within the outer loop, this inner loop prints a series of stars (*). The number of stars printed in each row corresponds to the current row number (i). For example, the first row will have one star, the second row two stars, and so on.

  1. Line Break After Each Row:

After printing the stars for a row, a newline is output using cout << endl; to move the cursor to the start of the next line. This ensures that each level of the pyramid appears on a new line.