Google News
logo
C++ Programs To Create Pyramid and Pattern
In the following examples of C++ programs to create pyramid and pattern:

Pyramid of stars :

Program :
#include <iostream>

using namespace std;

int main() {
    int n;

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

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }

        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }

        cout << endl;
    }

    return 0;
}
Output :
Enter the number of rows: 7
      *
     ***
    *****
   *******
  *********
 ***********
*************

This program prompts the user to enter the number of rows for the pyramid and then uses nested for loops to print out the pyramid of stars.


Right-angled triangle of numbers :

Program :
#include <iostream>

using namespace std;

int main() {
    int n;

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

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }

        cout << endl;
    }

    return 0;
}
Output :
Enter the number of rows: 7
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 

This program prompts the user to enter the number of rows for the triangle and then uses nested for loops to print out the right-angled triangle of numbers.


Diamond of stars :

#include <iostream>

using namespace std;

int main() {
    int n;

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

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }

        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }

        cout << endl;
    }

    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }

        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }

        cout << endl;
    }

    return 0;
}

Output :

Enter the number of rows: 7
      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *

This program prompts the user to enter the number of rows for the diamond and then uses nested for loops to print out the diamond of stars. The first loop prints the top half of the diamond, and the second loop prints the bottom half of the diamond.