C Program Hollow Hourglass pattern
C Program to print Hollow Hourglass pattern
Example :-
#include <stdio.h>
int main()
{
int i, j, k, rows;
printf("Enter the no. of rows: ");
scanf("%d", &rows);
printf("Output: \n\n");
for (i = 1; i <= rows; i++)
{
for (k = 1; k < i; k++)
printf(" ");
for (j = i; j <= rows; j++)
printf("* ");
printf("\n");
}
for (i = rows - 1; i >= 1; i--)
{
for (k = 1; k < i; k++)
printf(" ");
for (j = i; j <= rows; j++)
printf("* ");
printf("\n");
}
return 0;
}
C Code for Printing a Hollow Hourglass Shape
Explain Program
Step :1
int i, j,
k, rows;
- i, j, k:
Loop control variables
- rows:
Number of rows (input from the user)
Input from the user:
printf("Enter
the no. of rows: ");
scanf("%d",
&rows);
- The
user is ask to input the total number of row.
- example, if rows = 4, the pattern
heading:
printf("Output:
\n\n");
heading for clarity.
Upper Part of the Pattern:
for (i = 1;
i <= rows; i++)
{
for (k = 1; k < i; k++)
printf(" ");
for (j = i; j <= rows; j++)
printf("* ");
printf("\n");
}
loop prints an inverted right-aligned
triangle of stars.
- i goes
from 1 to rows — each iteration is a new row.
- k
prints spaces before the stars. The number of spaces increases each row to
push the stars to the right.
j
prints * from the current row number to rows. So, stars decrease in each row
Lower Part of the Pattern:
for (i =
rows - 1; i >= 1; i--)
{ for (k = 1; k < i; k++)
printf(" ");
for (j = i; j <= rows; j++)
printf("* ");
printf("\n");
}
loop
prints a right-aligned triangle of stars
This loop prints a right-aligned triangle
of stars (opposite of the first).
- Starts
from rows - 1 and goes down to 1.
- Prints
spaces first (decreasing).
- Then
prints stars (increasing count).
C Program to print Hollow Hourglass pattern
Output :-
C Program to print Hollow Hourglass pattern
Summary
- The upper
triangle shrinks (top-down).
- The lower
triangle grows (bottom-up).
- Both
are right-aligned because of the space handling (printf("
")).
- Nested
loops (loop inside loop)
- Controlling
spaces and stars to format patterns
- Symmetry in
output (first half decreasing, second half increasing)
- User
input and loops for dynamic patterns
Related Post :-
Comments
Post a Comment