Sandglass Pattern

Sandglass Pattern

Hard C Pattern Printing 38 views
Explanation Complexity

Problem Statement

* * * * *
 * * * *
  * * *
   * *
    *
   * *
  * * *
 * * * *
* * * * *
Inverted triangle above, normal below. Mirror image vertically.

Input Format

No input required.
Fixed number of rows.

Output Format

Star pattern with:

• Inverted triangle on top

• Normal triangle at bottom

• Vertically mirrored

Constraints

• Fixed rows (e.g. 5 up + 4 down)

• Nested loops only

Concept Explanation

The pattern is divided into two parts:
upper inverted triangle and lower normal triangle.

Step-by-Step Explanation

Upper Inverted Triangle

1.Use an outer loop for rows from 0 to n-1.

2.For each row i:

3.Print i leading spaces.

4.Print (n - i) stars with space after each star.

5.Move to the next line.

Lower Normal Triangle

1.Use another outer loop for rows from n-2 down to 0.

2.For each row i:

3.Print i leading spaces.

4.Print (n - i) stars with space after each star.

5.Move to the next line.

Concept Explanation

The pattern is divided into two parts:
upper inverted triangle and lower normal triangle.

Step-by-Step Explanation

Upper Inverted Triangle

1.Use an outer loop for rows from 0 to n-1.

2.For each row i:

3.Print i leading spaces.

4.Print (n - i) stars with space after each star.

5.Move to the next line.

Lower Normal Triangle

1.Use another outer loop for rows from n-2 down to 0.

2.For each row i:

3.Print i leading spaces.

4.Print (n - i) stars with space after each star.

5.Move to the next line.

Input / Output Format

Input Format
No input required.
Fixed number of rows.
Output Format
Star pattern with:

• Inverted triangle on top

• Normal triangle at bottom

• Vertically mirrored
Constraints
• Fixed rows (e.g. 5 up + 4 down)

• Nested loops only

Examples

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

Example Solution (Public)

C
#include <stdio.h>

int main() {
    int n = 5;   // height of triangle
    int i, j;

    for (i = 0; i < 2*n - 1; i++) {
        int spaces = (i < n) ? i : (2*n - 2 - i);
        int stars  = n - spaces;

        // leading spaces
        for (j = 0; j < spaces; j++)
            printf(" ");

        // stars
        for (j = 0; j < stars; j++)
            printf("* ");

        printf("n");
    }

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    int n = 5;   // height of triangle
    int i, j;

    for (i = 0; i < 2*n - 1; i++) {
        int spaces = (i < n) ? i : (2*n - 2 - i);
        int stars  = n - spaces;

        // leading spaces
        for (j = 0; j < spaces; j++)
            printf(" ");

        // stars
        for (j = 0; j < stars; j++)
            printf("* ");

        printf("n");
    }

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.