ad

Friday, April 11, 2025

C Program to print Hourglass Star Pattern

  C Program

C 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;
}


C Program to Print Hollow Square  Star Pattern

Explain Program

Step :1

#include <stdio.h>

 standard input/output library to use functions like printf() and scanf().

Step :2

int main()

{

  int n, a, k;

Declares three integer variables:

n: number of rows for the top half of the diamond.

 k: used for looping through rows.

 a: used for spaces and asterisks within each row.

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

 Stars: 2 * k - 1 stars

 k from 1 to n row has 2 * n - 1 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.

  Spaces: k spaces.

 Star 2 * (n - k) - 1 stars

 loop  from k = 1 to n - 1 because the middle line 

Step :6

  return 0;

}

Ends the program.

Step :7

C Program to print Hourglass Pattern

Output 

C Program to print Hourglass Pattern


Related Post :-

C program to print pascals triangle

C program to print inverted half

Print Inverted Half Pyramid of Stars Pattern

No comments:

Post a Comment