Print Diamond Star Pattern

PRINTING PATTERN:

      *

    ***

  *****

*******

  *****

    ***

      *

PREREQUISITE:

Basic knowledge of C language and use of loops.

ALGORITHM:

  1. Take the number of rows as input from the user and store it in any variable.(‘r‘ in this case).
  2. Run a loop ‘r’ number of times to iterate through each of the rows. From i=0 to i<r. The loop should be structured as for( i=0 ; i<r : i++).
  3. Use an if condition to to print the top half of the diamond. if (i<=r/2). Then run a loop from k=r/2 to k>i. The loop should be structured as for(k=r/2 ; k>i ; k–). Inside this loop print space.
  4. After this inside the if block run another loop from j=0 to j<=i*2. The loop should be structured as for(j=0 ; j<=i*2 ; j++)
  5. Inside this loop print star.
  6. Else run a different loop from k=r/2 to k<i, The loop should be structured as for( k=r/2;k<i ;k++).  Inside this loop print space
  7. Run another loop inside the else block from j=i to j<((r-i)*2)-1. The loop should be structured as for( j=0 ; j<((r-i)*2)-1 ; j++).
  8. Inside this loop print star.
  9. Inside the main loop print a newline to move to the next line after each row is printed.

CODE IN C:

#include<stdio.h>
int main()
{
int i,j,k,r;      //declaring integer variables i,j,k for loops and r for number of rows
printf("Enter the number of rows :\n"); //Asking user for input
scanf("%d",&r);                         //saving number of rows in variable r
for(i=0;i<r;i++)                       //outer loop for number of rows
   {
      if(i<=r/2)                       //if condition to print the top half of diamond
         {
            for(k=r/2;k>i;k--)          //nested loop for number of spaces
               {
                 printf(" ");           //printing spaces
               }
            for(j=0;j<=i*2;j++)         //nested loop for printing stars
               {
                  printf("*");          //printing stars
               }
         }
      else                              //else condition to print the bottom half of the diamond
         {
            for(k=r/2;k<i;k++)          //nested loop to print spaces
               {
                  printf(" ");         //printing spaces
               }
            for(j=0;j<((r-i)*2)-1;j++)  //loop to print star
               {
                  printf("*");        //printing stars
               }  
         }
      printf("\n");                   //printing newline
   }
}

TAKING INPUT:

DISPLAYING OUTPUT:

2 comments on “Print Diamond Star Pattern”


  • Arthi

    #python
    n = int(input())
    c1 = 1
    c = n//2+1
    for i in range(c):
    print(‘ ‘*(c-i-1)+’*’*(2*i+1))
    for j in range(n-2,0,-2):
    print(‘ ‘*c1+’*’*j)
    c1 +=1


  • Tejasri

    python
    n=int(input())
    a=n+n-1
    for i in range(a):
    if i<n:
    print(" "*(n-1-i)+"*"*(i+i+1))
    else:
    print(" "*(i+1-n)+"*"*(2*(a-i)-1))