Summary: This C program prints an hourglass pattern using alphabets. The pattern begins with 13 letters and narrows down toward the center, then expands symmetrically back outward. It demonstrates nested loops, character arithmetic, and space formatting.
#include <stdio.h>
int main() {
int i, j, space;
int max = 13; // number of letters in the first and last row
int lines = (max + 1) / 2; // total number of lines in upper/lower half
// Upper part
for (i = 0; i < lines; i++) {
space = i * 2;
for (j = 0; j < space; j++) {
printf(" ");
}
for (j = 0; j < max - i * 2; j++) {
printf("%c ", 'A' + j);
}
printf("\n");
}
// Lower part
for (i = lines - 2; i >= 0; i--) {
space = i * 2;
for (j = 0; j < space; j++) {
printf(" ");
}
for (j = 0; j < max - i * 2; j++) {
printf("%c ", 'A' + j);
}
printf("\n");
}
return 0;
}
Looping for Pattern Generation:
The program constructs the hourglass pattern using nested for
loops. The outer loop controls the rows, while inner loops manage spacing and alphabet output.
Character Arithmetic:
The expression 'A' + j
utilizes ASCII arithmetic to print consecutive alphabet letters dynamically for each row.
Upper and Lower Halves:
The upper half starts with the full width and reduces characters while increasing indentation. The lower half mirrors this logic in reverse to form the hourglass shape.
Spacing Logic:
The number of spaces increases with each row to center-align the characters and achieve the hourglass visual effect. This is done by printing i * 2
spaces before each row.
Pattern Control with 'max':
The variable max
determines how wide the pattern starts and ends. It should be an odd number to maintain symmetry in the hourglass.