C Program to Print Diamond Pattern

«
»

Pattern problems are one of the most common problems encountered by programmers. This article contains a diamond pattern problem in C with its proper approach, algorithm and codes.

Problem Description

Write a C program that prints a diamond pattern upon receiving number of rows as input.

Problem Solution

Algorithm:
1. Take the number of rows as input.
2. Store the number in a variable.
3. Inside a loop, print the spaces and then the asterisks.
4. Repeat the process until the number is equal to 0.
5. Exit.

There are several ways to print a diamond pattern program in C language. Let’s take a detailed look at all the approaches to printing a diamond pattern in C.

Method 1: Print Diamond Pattern in C using For Loop (Naive Approach)

In this approach, we use a for loop to print the spaces and then the asterisks.

Examples:
Input:
Enter the number: 5

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Output:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Input:
Enter the number: 3

Output:

  *
 ***
*****
 ***
  *
Program/Source Code

Here is source code of the C Program to print diamond pattern using for loop. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Print Diamond Pattern using For Loop
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. int main()
  8. {
  9.     int number, i, k, count = 1;
  10.  
  11.     printf("Enter number of rows: \n");
  12.     scanf("%d", &number);
  13.     count = number - 1;
  14.     for (k = 1; k <= number; k++)
  15.     {
  16.         for (i = 1; i <= count; i++)
  17.             printf(" ");
  18.         count--;
  19.         for (i = 1; i <= 2 * k - 1; i++)
  20.             printf("*");
  21.         printf("\n");
  22.      }
  23.      count = 1;
  24.      for (k = 1; k <= number - 1; k++)
  25.      {
  26.          for (i = 1; i <= count; i++)
  27.              printf(" ");
  28.          count++;
  29.          for (i = 1 ; i <= 2 *(number - k)-  1; i++)
  30.              printf("*");
  31.          printf("\n");
  32.       }
  33.       return 0;
  34. }
Program Explanation

1. Take the number of rows as input and store in the variable number.
2. Firstly decrement the variable number by 1 and assign this value to the variable count.
3. Use this variable count as terminator in the for loop to print ” “.
4. Decrement count by 1.
5. Use another for loop starting from 1 to (2*k-1) to print “*”.
6. Do steps 3, 4, and 5 inside the for loop starting from 1 to variable number.
7. Steps 2-6 are used to print half of the diamond pattern.
8. For the next half, assign the variable count by 1.
9. Use this variable count as terminator in the for loop to print ” “.
10. Increment count by 1.
11. Use another for loop starting from 1 to (2*(number-k)-1) to print “*”.
12. Do steps 8-11 inside the for loop starting from 1 to value (number-1).

Time Complexity: O(n2)
The time complexity of the diamond pattern program is O(n2), because we are traversing rows and columns of a grid to print spaces” ” and stars ‘*’.

advertisement

Space Complexity: O(1)
The space complexity of the diamond pattern program is O(1) because no extra space is used.

Run Time Testcases

Testcase 1: In this case, we enter the number of rows as “5” to print the diamond pattern.

Enter number of rows: 5
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Testcase 2: In this case, we enter the number of rows as “3” to print the diamond pattern.

Enter number of rows: 3
  *
 ***
*****
 ***
  *

advertisement
Method 2: Print Diamond Pattern using While Loop

In this approach, we will use a while loop to print the spaces and then the asterisks and also make a separate function for printing the diamond pattern.

Methods used:
int diamondPattern(int) – This function will print the diamond pattern.

Example:
Input:
Enter the number: 8

Output:

               * 
             * * * 
           * * * * * 
         * * * * * * * 
       * * * * * * * * * 
     * * * * * * * * * * * 
   * * * * * * * * * * * * * 
 * * * * * * * * * * * * * * * 
   * * * * * * * * * * * * * 
     * * * * * * * * * * * 
       * * * * * * * * * 
         * * * * * * * 
           * * * * * 
             * * * 
               *
Program/Source Code

Here is source code of the C Program to print diamond pattern using while loop. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Print Diamond Pattern using while Loop
  3.  */
  4.  
  5. # include <stdio.h>
  6. void diamondPattern(int num)
  7. {
  8.     int str = 1;
  9. 	while(str <= num)
  10. 	{
  11. 		int i = 1;
  12. 		while(i ++ <= (num - str) * 2 + 1)
  13. 			printf(" ");
  14. 		i = 0;
  15. 		while(i ++ < 2 * str - 1)
  16. 			printf("* ");
  17. 		str ++;
  18. 		printf("\n");
  19. 	}
  20. 	str = num - 1;
  21. 	while(str != 0)
  22. 	{
  23. 		int i = 1;
  24. 		while(i ++ <= (num - str) * 2 + 1)
  25. 			printf(" ");
  26. 		i = 0;
  27. 		while(i ++ < 2 * str - 1)
  28. 			printf("* ");
  29. 		str --;
  30. 		printf("\n");
  31. 	}
  32. }
  33.  
  34. int main(void)
  35. {
  36.     int number;
  37.     printf("Enter the number: ");
  38.     scanf("%d", &number);
  39.     diamondPattern(number);
  40. }
Program Explanation

1. Take the number of rows as input and store in the variable number.
2. The function diamondPattern prints the diamond pattern.
3. In the function diamondPattern, until the number of stars is less than equal to the argument a while loop executes which prints the spaces and stars according to the regular format.
4. In another while loop, the process is the same but the loop termination condition is now when the stars are equal to zero.
5. The spaces and stars are printed according to format.

Time Complexity: O(n2)
The time complexity of the diamond pattern program is O(n2), because we are traversing rows and columns of a grid to print spaces” ” and stars ‘*’.

Space Complexity: O(1)
The space complexity of the diamond pattern program is O(1) because no extra space is used.

Run Time Testcases

Testcase 1: In this case, we enter the number of rows as “8” to print the diamond pattern.

Enter the number: 8
               * 
             * * * 
           * * * * * 
         * * * * * * * 
       * * * * * * * * * 
     * * * * * * * * * * * 
   * * * * * * * * * * * * * 
 * * * * * * * * * * * * * * * 
   * * * * * * * * * * * * * 
     * * * * * * * * * * * 
       * * * * * * * * * 
         * * * * * * * 
           * * * * * 
             * * * 
               *

Testcase 2: In this case, we enter the number of rows as “6” to print the diamond pattern.

Enter the number: 6
           * 
         * * * 
       * * * * * 
     * * * * * * * 
   * * * * * * * * * 
 * * * * * * * * * * * 
   * * * * * * * * * 
     * * * * * * * 
       * * * * * 
         * * * 
           *

Method 3: Diamond Pattern using Recursion

In this approach we use recursion to solve our problem along with a helping function to print multiple characters.

Methods used:

  • int printMul(char, int) – Prints the specified character multiple times as specified by the argument.
  • int printDiamond(int) – Prints the diamond pattern.
Program/Source Code

Here is source code of the C Program to print diamond pattern using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Print Diamond Pattern using recursion
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. void printMul(char a, int n)
  8. {
  9.     for (int i = 0; i < n; i++)
  10.         printf("%c ", a);
  11. }
  12.  
  13. void printDiamond(int a, int b)
  14. {
  15.     printMul(' ', a - 1);
  16.     printMul('*', 2 * b + 1);
  17.     printf("\n");
  18.     if (a == 1)
  19.         return;
  20.     printDiamond(a - 1, b + 1);
  21.     printMul(' ', a - 1);
  22.     printMul('*', 2 * b + 1);
  23.     printf("\n");
  24. }
  25.  
  26. int main(void)
  27. {
  28.     int num;
  29.     printf("Enter the number of rows: ");
  30.     scanf("%d", &num);
  31.     printDiamond(num, 0);
  32. }
Program Explanation

1. Take the number of rows as input and store in the variable num.
2. The number is then passed to the function printDiamond which prints the diamond pattern.
3. In printDiamond, the function printMul is used to print the spaces and the asterisks.
4. In the printDiamond function, the number of spaces are a – 1 and the number of asterisks are 2 * b + 1.
5. The terminating condition is when a = 1. The printing is done again here.
6. The function works like a stack, the second half of the first call of the function is executed at the last. Thus a nice diamond structure follows.

Time Complexity: O(n2)
The time complexity of the diamond pattern program is O(n2), because we are traversing rows and columns of a grid to print spaces” ” and stars ‘*’.

Space Complexity: O(1)
The space complexity of the diamond pattern program is O(1) because no extra space is used.

Run Time Testcases

Testcase 1: In this case, we enter the number of rows as “4” to print the diamond pattern.

Enter the number: 4
       * 
     * * * 
   * * * * * 
 * * * * * * * 
   * * * * * 
     * * * 
       *

Testcase 2: In this case, we enter the number of rows as “6” to print the diamond pattern.

Enter the number: 12
                      * 
                    * * * 
                  * * * * * 
                * * * * * * * 
              * * * * * * * * * 
            * * * * * * * * * * * 
          * * * * * * * * * * * * * 
        * * * * * * * * * * * * * * * 
      * * * * * * * * * * * * * * * * * 
    * * * * * * * * * * * * * * * * * * * 
  * * * * * * * * * * * * * * * * * * * * * 
* * * * * * * * * * * * * * * * * * * * * * * 
  * * * * * * * * * * * * * * * * * * * * * 
    * * * * * * * * * * * * * * * * * * * 
      * * * * * * * * * * * * * * * * * 
        * * * * * * * * * * * * * * * 
          * * * * * * * * * * * * * 
            * * * * * * * * * * * 
              * * * * * * * * * 
                * * * * * * * 
                  * * * * * 
                    * * * 
                      *

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.