Simple Triangle/Half Pyramid (With C++ Code) | Pattern Printing Programs

In this tutorial we will understand how to code a triangle pattern and different variations. It is also known as Half Pyramid Pattern. We will first dry run the for loops and see step by step how the pattern is generated. Later we will also write a program to print this pattern in C++ Programming Language.

C++ Program for printing 4 different Triangle/Half Pyramid Programs –
#include <iostream>
using namespace std;

void halfPyramidPattern1(int n)
{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        cout << endl;
    }
}
void halfPyramidPattern2(int n)
{
    for (int i = n; i >= 1; i--) {
        for (int j = i; j > 0; j--) {
            cout << "*";
        }
        cout << endl;
    }
}
void halfPyramidPattern3(int n)
{
    for (int i = 1; i <= n; i++) {
        for (int k = n - i; k > 0; k--) {
            cout << " ";
        }
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        cout << endl;
    }
}

void halfPyramidPattern4(int n)
{
    for (int i = n; i >= 1; i--) {
        for (int k = n - i; k > 0; k--) {
            cout << " ";
        }
        for (int j = i; j > 0; j--) {
            cout << "*";
        }
        cout << endl;
    }
}

int main()
{
    int num;
    cout << "Enter number of levels of the pattern :" << endl;
    cin >> num;
    halfPyramidPattern1(num);
    cout << endl;
    halfPyramidPattern2(num);
    cout << endl;
    halfPyramidPattern3(num);
    cout << endl;
    halfPyramidPattern4(num);

    return 0;
}
YouTube video tutorial –

Leave a Reply

Your email address will not be published. Required fields are marked *