Print Diamond Pattern

Print Diamond Pattern

Medium C++ Pattern Printing 28 views
Explanation Complexity

Problem Statement

Print complete diamond shape.
Real Life: Combining pyramid and inverted pyramid.

Input Format

An integer n (number of rows for the upper half).

Output Format

Complete diamond shape using *.

Example

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

Constraints

• n ≥ 1

• Use loops only

Concept Explanation

A complete diamond is made by combining a pyramid and an inverted pyramid.
Stars increase first, then decrease, while spaces keep the shape centered.

Step-by-Step Explanation

Upper Half (Pyramid)

1.Loop row i from 1 to n.

2.Print (n - i) spaces.

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

4.Move to next line.

Lower Half (Inverted Pyramid)
5. Loop row i from n-1 to 1.
6. Print (n - i) spaces.
7. Print (2*i - 1) stars.
8. Move to next line.

Concept Explanation

A complete diamond is made by combining a pyramid and an inverted pyramid.
Stars increase first, then decrease, while spaces keep the shape centered.

Step-by-Step Explanation

Upper Half (Pyramid)

1.Loop row i from 1 to n.

2.Print (n - i) spaces.

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

4.Move to next line.

Lower Half (Inverted Pyramid)
5. Loop row i from n-1 to 1.
6. Print (n - i) spaces.
7. Print (2*i - 1) stars.
8. Move to next line.

Input / Output Format

Input Format
An integer n (number of rows for the upper half).
Output Format
Complete diamond shape using *.
Constraints
• n ≥ 1

• Use loops only

Examples

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

Example Solution (Public)

C++
void pattern_q8_diamond() {
    int n = 5;
    
    // Upper pyramid
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
    
    // Lower inverted pyramid
    for(int i = n - 1; i >= 1; i--) {
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
}

Official Solution Code

void pattern_q8_diamond() {
    int n = 5;
    
    // Upper pyramid
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
    
    // Lower inverted pyramid
    for(int i = n - 1; i >= 1; i--) {
        for(int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.