Print Pyramid Pattern (Centered)

Print Pyramid Pattern (Centered)

Medium C++ Pattern Printing 45 views
Explanation Complexity

Problem Statement

Print centered pyramid of stars.
Real Life: Classic pyramid shape.

Input Format

An integer n (number of rows).

Output Format

Centered pyramid made of *.

Example

4
   *
  ***
 *****
*******

Constraints

• n ≥ 1

• Use loops only

Concept Explanation

A centered pyramid has stars in the middle.
Each next row has 2 more stars than the previous row,
and one less space on the left to keep it centered.

Step-by-Step Explanation

1.Take input n.

2.Loop row i from 1 to n.

3.Print (n - i) spaces.

4.Print (2*i - 1) stars.

5.Move to next line.

Concept Explanation

A centered pyramid has stars in the middle.
Each next row has 2 more stars than the previous row,
and one less space on the left to keep it centered.

Step-by-Step Explanation

1.Take input n.

2.Loop row i from 1 to n.

3.Print (n - i) spaces.

4.Print (2*i - 1) stars.

5.Move to next line.

Input / Output Format

Input Format
An integer n (number of rows).
Output Format
Centered pyramid made of *.
Constraints
• n ≥ 1

• Use loops only

Examples

Input:
4
Output:
* *** ***** *******

Example Solution (Public)

C++
void pattern_q6_pyramid() {
    int n = 5;
    
    for(int i = 1; i <= n; i++) {
        // Print spaces
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        // Print stars
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
}

Official Solution Code

void pattern_q6_pyramid() {
    int n = 5;
    
    for(int i = 1; i <= n; i++) {
        // Print spaces
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        // Print stars
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.