To print an Hourglass Pattern in C, we use nested loops. The outer loop controls the rows and the inner loops control the spaces and stars (*) to form the pattern.
In this example,
for
loops, where the outer loop runs from n
to 1 and the inner loops control the spaces and stars in each row.#include <stdio.h>
void printHourglass(int n) {
for (int i = n; i >= 1; i--) {
for (int j = 0; j < n - i; j++)
printf(" ");
for (int j = 0; j < 2 * i - 1; j++)
printf("*");
printf("\n");
}
for (int i = 2; i <= n; i++) {
for (int j = 0; j < n - i; j++)
printf(" ");
for (int j = 0; j < 2 * i - 1; j++)
printf("*");
printf("\n");
}
}
int main() {
int n = 5;
printHourglass(n);
return 0;
}
********* ******* ***** *** * *** ***** ******* *********
In this tutorial, we learned How to print Hour Glass Pattern in C language with well detailed examples.