Program to Print Full Pyramid Using CPP

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn how to write a C++ program to print a full pyramid using *. The program will prompt the user to enter the number of rows they want to print and then it will print a full pyramid with that many rows.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/ControlFlowGroup -.-> cpp/for_loop("For Loop") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/for_loop -.-> lab-96244{{"Program to Print Full Pyramid Using CPP"}} cpp/output -.-> lab-96244{{"Program to Print Full Pyramid Using CPP"}} cpp/user_input -.-> lab-96244{{"Program to Print Full Pyramid Using CPP"}} cpp/code_formatting -.-> lab-96244{{"Program to Print Full Pyramid Using CPP"}} end

Including the necessary header files

In this step, you need to include the necessary header files.

#include<iostream>
using namespace std;

Creating the main function

In this step, you will create the main function which is the entry point of the program.

int main()
{
    int space, rows;

    cout <<"Enter number of rows: ";
    cin >> rows;

    for(int i = 1, k = 0; i <= rows; ++i, k = 0)
    {
        for(space = 1; space <= rows-i; ++space)
        {
            cout <<"  ";
        }

        while(k != 2*i-1)
        {
            cout << "* ";
            ++k;
        }
        cout << endl;
    }

    return 0;
}

Testing the program

To test the program, run the following command in the terminal.

g++ main.cpp -o main && ./main

You will see the following output:

Enter number of rows: 5
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

Full code

Here is the full code for main.cpp.

#include<iostream>
using namespace std;

int main()
{
    int space, rows;

    cout <<"Enter number of rows: ";
    cin >> rows;

    for(int i = 1, k = 0; i <= rows; ++i, k = 0)
    {
        for(space = 1; space <= rows-i; ++space)
        {
            cout <<"  ";
        }

        while(k != 2*i-1)
        {
            cout << "* ";
            ++k;
        }
        cout << endl;
    }

    return 0;
}

Summary

In this lab, you have learned how to write a C++ program to print a full pyramid using *, by prompting the user to enter the number of rows they want to print and then printing a full pyramid with that many rows. Now you can practice using this program to create similar patterns for your own projects.