Print the Diamond Pattern Using For Loop in C Programming


This program is written in the C programming language, and it is used to print a hourglass shape of asterisks (*) with a user-specified number of rows.

  • The program starts by including the standard input/output header file, "stdio.h". Then, the main() function is defined. Inside the main function, three variables are declared: "i", "j" are used as counter variables in nested for loops, and "n" is used to store the user input value.
  • The program then prompts the user to enter a number using the printf() function and stores the value in the "n" variable using the scanf() function. The first for loop is then used to repeatedly execute the code inside the loop for the number of times specified by the user. The for loop starts with "i" initialized to 1, and the loop continues until "i" is less than or equal to "n".
  • The second for loop is nested inside the first for loop, and it is used to create the indentation, before the hourglass shape. The loop starts with "j" initialized to 1 and it continues until "j" is less than or equal to (n-i).
  • The third and fourth for loops are nested inside the first for loop, and it is used to print the asterisks (*) to form the upper half of hourglass shape. The third loop starts with "j" initialized to 1 and it continues until "j" is less than i and the fourth loop starts with "j" initialized to 1 and it continues until "j" is less than or equal to i.
  • The fifth for loop starts with i value 1 and it creates the lower half of the hourglass shape. The nested loop creates the indentation before the hourglass shape and the second nested loop prints the asterisks (*) to form the lower hal half of hourglass shape.

Source Code

#include<stdio.h>
int main()
{
  int i,j,n;
  printf("\nEnter the value:");
  scanf("%d",&n);
  for(i=1;i<=n;i++)
  {
    printf("\n");
    for(j=1;j<=(n-i);j++)
    {
        printf("  ");
    }
    for(j=1;j<i;j++)
    {
        printf(" *");
    }
    for(j=1;j<=i;j++)
    {
        printf(" *");
    }
    }
    for(i=1;i<=n;i++)
    {
      printf("\n");
      for(j=1;j<=i;j++)
      {
          printf("  ");
      }
      for(j=n;j>i;j--)
      {
          printf(" *");
      }
      for(j=1;j<(n-i);j++)
      {
          printf(" *");
      }
    }
    return 0;
}
To download raw file Click Here

Output

Enter the value:5
            *
	   ***
	  *****
	 *******
	*********
	 *******
	  *****
	   ***
	    *

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C