Print Diamond Pattern

Print Diamond Pattern

Hard C++ Control Flow 34 views
Explanation Complexity

Problem Statement

Print diamond shape using stars.
Real Life: Making decorative patterns.

Input Format

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

Output Format

Diamond pattern made of *

Example

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

Constraints

• n ≥ 1

• Use loops only

Concept Explanation

A diamond has two parts:

• Upper half (increasing stars)

• Lower half (decreasing stars)
Spaces are used to keep the shape centered.

Step-by-Step Explanation

1.Take input n.

2.Upper half (rows 1 to n):

• Print (n - i) spaces.

• Print (2*i - 1) stars.

3.Lower half (rows n-1 to 1):

• Print (n - i) spaces.

• Print (2*i - 1) stars.

4.Move to next line after each row.

Concept Explanation

A diamond has two parts:

• Upper half (increasing stars)

• Lower half (decreasing stars)
Spaces are used to keep the shape centered.

Step-by-Step Explanation

1.Take input n.

2.Upper half (rows 1 to n):

• Print (n - i) spaces.

• Print (2*i - 1) stars.

3.Lower half (rows n-1 to 1):

• Print (n - i) spaces.

• Print (2*i - 1) stars.

4.Move to next line after each row.

Input / Output Format

Input Format
An integer n (number of rows for the upper half).
Output Format
Diamond pattern made of *
Constraints
• n ≥ 1

• Use loops only

Examples

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

Example Solution (Public)

C++
void control_q13_diamond_pattern() {
    int rows = 5;
    
    // Upper part
    for(int i = 1; i <= rows; i++) {
        // Print spaces
        for(int j = 1; j <= rows - i; j++) {
            cout << " ";
        }
        // Print stars
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
    
    // Lower part
    for(int i = rows - 1; i >= 1; i--) {
        // Print spaces
        for(int j = 1; j <= rows - i; j++) {
            cout << " ";
        }
        // Print stars
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
}

Official Solution Code

void control_q13_diamond_pattern() {
    int rows = 5;
    
    // Upper part
    for(int i = 1; i <= rows; i++) {
        // Print spaces
        for(int j = 1; j <= rows - i; j++) {
            cout << " ";
        }
        // Print stars
        for(int k = 1; k <= 2*i - 1; k++) {
            cout << "*";
        }
        cout << endl;
    }
    
    // Lower part
    for(int i = rows - 1; i >= 1; i--) {
        // Print spaces
        for(int j = 1; j <= rows - 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.