An hourglass pattern is a symmetrical star pattern shaped like an hourglass, where stars form a wide top, narrow middle, and wide bottom. Printing this pattern helps beginners understand nested loops, conditional printing, and alignment in C.
Understanding The Problem
The program should take the number of rows for the top half of the hourglass and print stars forming the hourglass. The top half is an inverted pyramid, and the bottom half is a normal pyramid. Proper spacing ensures symmetry.
Steps to Solve the Problem:
- Take the number of rows for the top half from the user.
- Print the top half as an inverted pyramid using nested loops.
- Print the bottom half as a normal pyramid using nested loops.
- Control spaces and stars carefully to maintain symmetry.
Solution: Using Nested Loops
Nested loops are used to control spaces and stars for both halves of the hourglass.
#include <stdio.h>
int main() {
int n;
printf("Enter number of rows for the top half: ");
scanf("%d", &n);
// Top half (inverted pyramid)
for(int i = n; i >= 1; i--) {
// Print leading spaces
for(int j = 1; j <= n - i; j++) {
printf(" ");
}
// Print stars
for(int j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
printf("\n");
}
// Bottom half (normal pyramid)
for(int i = 2; i <= n; i++) {
// Print leading spaces
for(int j = 1; j <= n - i; j++) {
printf(" ");
}
// Print stars
for(int j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
printf("\n");
}
return 0;
}
In this program, the top half prints stars in decreasing order with increasing spaces to form an inverted pyramid. The bottom half prints stars in increasing order with decreasing spaces to form a normal pyramid. Together, they create a symmetrical hourglass pattern.
FAQs
Q1: Can we use a character other than *
?
Yes, any symbol can replace *
to create an hourglass with a different character.
Q2: Can the hourglass be hollow?
Yes, using conditional statements, you can print only the borders to create a hollow hourglass.
Q3: Can we adjust the size of the hourglass?
Yes, increasing the number of rows will create a taller and wider hourglass pattern.
Conclusion
This program demonstrates how to print an hourglass pattern using nested loops. By controlling spaces and stars for both halves, a symmetrical and visually appealing hourglass is created. The concept can be extended to hollow hourglasses or hourglasses with different symbols.
References & Additional Resources
- C Programming Tutorial – Covers loops, nested loops, and pattern printing in C.
- GeeksforGeeks – Pattern Programs in C – Examples of complex star patterns including hourglass patterns.
- TutorialsPoint – C Loops – Explanation of nested loops and alignment techniques in C.