Print an Hourglass Number Pattern in C
To print an hourglass number pattern in C, we use nested loops to control the printing of numbers and spaces. The pattern consists of two symmetrical triangular sections—one decreasing and one increasing—forming an hourglass shape. We control the number of spaces and digits in each row dynamically using loops.
Examples of Printing an Hourglass Number Pattern
1. Basic Hourglass Number Pattern
In this example, we print a simple hourglass number pattern where numbers decrease in a triangular fashion and then increase, forming the shape of an hourglass.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n = 5; // Number of rows in the upper part
// Upper half
for (int i = n; i >= 1; i--) {
// Printing leading spaces
for (int j = 0; j < n - i; j++) {
printf(" ");
}
// Printing numbers
for (int j = i; j >= 1; j--) {
printf("%d ", j);
}
for (int j = 2; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
// Lower half
for (int i = 2; i <= n; i++) {
// Printing leading spaces
for (int j = 0; j < n - i; j++) {
printf(" ");
}
// Printing numbers
for (int j = i; j >= 1; j--) {
printf("%d ", j);
}
for (int j = 2; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare an integer variable
n
to define the number of rows in the top half of the hourglass. - The first
for
loop prints the upper half of the hourglass by decreasing the number of printed numbers per row. - Inside the loop, we print spaces (
printf(" ")
) before printing numbers to align the pattern. - Two inner loops print numbers in decreasing and increasing order symmetrically.
- The second
for
loop prints the lower half by reversing the process of the upper half.
Output:
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
Conclusion
In this tutorial, we explored different ways to print an hourglass number pattern in C:
- Basic Hourglass Pattern: Numbers decreasing and then increasing symmetrically.
- Hourglass with Increasing Digits: Numbers increasing from 1 to maximum in each row.
Using nested loops and conditional logic, we can create various hourglass patterns dynamically.