C++ Reverse Half Pyramid Pattern Using Asterix

Beginner

Introduction

In this lab, you will learn how to print a Reverse Half Pyramid pattern using asterisks (*) by writing a C++ program. All such patterns using * or alphabets or numbers are achieved by making use of the nested loop structures by knowing how to iterate and until where to iterate.

Set up the Project

Open the terminal and create a new C++ source file named pyramid.cpp in the ~/project directory:

cd ~/project
touch pyramid.cpp

Open the file with a text editor.

Write the Code

Add the following code to the pyramid.cpp file.

//Cpp Reverse Half Pyramid Pattern Using Asterix
//Nested Loop Structure
#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to print a Reverse Half Pyramid using * ===== \n\n";

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

    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;
    cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";

    //outer loop is used to move to a particular row
    for (i = 1; i <= rows; i++)
    {
        //to display that the outer loop maintains the row number
        cout << "Row ## " << i << " contains " << (rows - i + 1) << " stars :  ";

        //inner loop is used to decide the number of * in a particular row
        for (j = rows; j >= i; j--)
        {
            cout << "* ";
        }

        cout << endl;
    }

    cout << "\n\n";

    return 0;
}

The program takes the number of rows rows as input and displays the reverse half pyramid up to the number of rows entered by the user using *.

Save and Compile the Code

Save the changes to the pyramid.cpp file and exit the text editor. Compile the code using the following command in the terminal:

g++ pyramid.cpp -o pyramid

Run the Code

Execute the compiled program by typing the following command in the terminal:

./pyramid

Enter the number of rows for the pyramid and see the program output the reverse half pyramid pattern containing that many rows.

Summary

Congratulations! You have successfully completed the lab to print a Reverse Half Pyramid pattern using asterisks using C++.

The nested loop structure is very useful for creating patterns like this one. It is important to understand how the loops work and how to iterate through them for building more complex patterns.

Other Tutorials you may like