C++ Half Pyramid Pattern Using Numbers

Beginner

Introduction

In this lab, you will learn how to print a half pyramid structure using numbers, in the C++ programming language. You will be using nested loop structures to iterate and decide the number of rows and columns in each row.

Create a new C++ file in the project directory

Navigate to the project directory using the cd command in the terminal and create a new C++ file called "half_pyramid_numbers.cpp" using the command touch half_pyramid_numbers.cpp.

cd ~/project
touch half_pyramid_numbers.cpp

Enter the code

Enter the following code into the "half_pyramid_numbers.cpp" file to print a half pyramid structure using numbers:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the Half Pyramid using Numbers Program :-)\n\n\n";
    cout << " =====  Program to print a Half Pyramid using numbers ===== \n\n";

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

    //prompt the user to enter the number of rows
    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;

    //outer loop is used to move to a particular row
    for (i = 1; i <= rows; i++)
    {
        //inner loop is used to decide the number of columns in a particular row
        for (j = 1; j <= i; j++)
        {
            cout << j << " "; //printing the column number within each row
        }

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

    cout << "\n\n";

    return 0; //end the program
}

Summary

Congratulations! You have successfully completed the Half Pyramid Pattern using Numbers Lab in C++. In this lab, you learned how to use nested loop structures to print a half pyramid structure using numbers. You are now ready to move on to more complex patterns and structures.

Other Tutorials you may like