C Program to print Hourglass Star Pattern
C Program Pattern
Program to print 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;}
Explain Program
#include <stdio.h>
standard input/output library to use functions
like printf() and scanf().
int main()
{
int n, a, k;
Declares three integer variables:
n: number of rows for the top half of the diamond.
Step :3
printf("Enter
number of rows\n");
scanf("%d", &n);
input the number of rows determines the size of the diamond
Step :4
for (k = 1; k <=
n; k++)
{
for (a = 1; a
<= n-k; a++)
printf("
");
for (a = 1; a
<= 2*k-1; a++)
printf("*");
printf("\n");
}
loop prints the top half of the diamond.
Spaces: n - k spaces before stars
Step :5
Bottom Half of the Diamond
for (k = 1; k <= n - 1; k++)
{
for (a = 1; a
<= k; a++)
printf("
");
for (a = 1 ; a
<= 2*(n-k)-1; a++)
printf("*");
printf("\n");
}
This loop print the bottom half of the diamond.
loop from k = 1 to n - 1 because the middle line
return 0;
}
Ends the program.
Output

Post a Comment