C Program to Print Diamond Number Pattern

Ex: Write a C program to print diamond number pattern. How to write a C program to print diamond number pattern. C program to print diamond number pattern.


Input from user:

Enter the number: 5


Expected output:

              1

            1  2

          1  2  3

        1  2  3  4

      1  2  3  4  5

        1  2  3  4

          1  2  3

            1  2

              1




  Step by step logic of the given:


For better understanding i have devided this code in two parts.


To print upper half part:

              1

            1  2

          1  2  3

        1  2  3  4

      1  2  3  4  5


1. Accept input number from user.


2. Run outer for loop from  1 to no which shows rows in pattern:

for(i=1;i<=no;i++)


3. Run inner for loop from i to no-1 to print spaces:

for(j=i;j<no;j++)

{

printf(" ");

}


4. Run another inner for loop from 1 to i which shows columns in pattern:

for(k=1;k<=i;k++)


5. Inside the second inner for loop print value of k with one space:

printf("%d ",k);


6. After that outside the block of  inner for loop print next line \n for print new row.



To print lower half part:


        1  2  3  4

          1  2  3

            1  2

              1


1. Run outer loop from 1 to no-1 which shows rows in pattern:

for(i=1;i<no;i++)


2. Run inner for loop from 1 to i to print spaces:

for(j=1;j<=i;j++)

{

        printf(" ");

}


3. Run another one inner for loop from 1 to no-i and inside the loop print value of  k :

for(k=1;k<=no-i;k++)

{

        printf("%d ",k);

}


4. Last print \n for new row.




  Program to print diamond number pattern:


#include<stdio.h>

void main()

{

int no,i,j,k;

printf("Enter the number:");

scanf("%d",&no);

/*To print upper part*/

for(i=1;i<=no;i++)

{

for(j=i;j<no;j++)

{

printf(" ");

}

for(k=1;k<=i;k++)

{

printf("%d ",k);

}

/*For next row*/ printf("\n");

}

     /*To print lower part*/

     for(i=1;i<no;i++)

     {

         for(j=1;j<=i;j++)

         {

         printf(" ");

         }

         for(k=1;k<=no-i;k++)

         {

         printf("%d ",k);

         }

     /*For next row*/

     printf("\n");

     }

}


Above program shows the following output:


C program to print diamond number pattern, Star pattern programs in C




No comments:

Post a Comment

If you have any doubts, please discuss here...👇