Program to print pyramid pattern

Write to program to print the pyramid pattern formed of stars
Example:

Input:  n = 6
Output:
       *
       * *
       * * *
       * * * *
       * * * * *
       * * * * * * 
       * * * * *
       * * * *
       * * *
       * * 
       *

We strongly recommend you to minimize your browser and try this yourself first.

The idea is to use two for loops for every part of the pyramid. The two parts may be classified as upper part and lower part

C++

// C++ program to print Pyramid pattern
#include<iostream>
using namespace std;

void pattern(int n)
{    
    // For printing the upper part of the pyramid
    for (int i = 1; i<n; i++){
        for (int j = 1 ; j < i+1 ; j++){
            cout <<" * ";
        }
        cout << endl ;
    }

    // For printing the lower part of pyramid
    for (int i = n ; i > 0 ; i--){
        for (int j = i ; j > 0 ; j--){
            cout <<  " * ";
        }
        cout << endl ;
    }
}

// Driver program 
int main()
{
    pattern(6);
    return 0;
}

Python

# Python program to print Pyramid pattern

def pattern(n):
   
    # For printing the upper part of pyramid
    for i in range (1, n+1):
        for j in range (1, i+1):
            print " *",
        print
    
    # for printing the middle and lower part of pyramid
    for i in range (n, 1, -1):
        for j in range (i, 1, -1):
            print " *",
        print

# Driver program
pattern(6)


Output:
 *
 *  *
 *  *  *
 *  *  *  *
 *  *  *  *  *
 *  *  *  *  *  *
 *  *  *  *  *
 *  *  *  *
 *  *  *
 *  *
 *

This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.