You are here

C program to print diamond pattern

Diamond pattern in C language: This code prints diamond pattern of stars. The diamond shape is as follows:

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

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int n, c, k, space = 1;
  6.  
  7.   printf("Enter number of rows\n");
  8.   scanf("%d", &n);
  9.  
  10.   space = n - 1;
  11.  
  12.   for (k = 1; k <= n; k++)
  13.   {
  14.     for (c = 1; c <= space; c++)
  15.       printf(" ");
  16.  
  17.     space--;
  18.  
  19.     for (c = 1; c <= 2*k-1; c++)
  20.       printf("*");
  21.  
  22.     printf("\n");
  23.   }
  24.  
  25.   space = 1;
  26.  
  27.   for (k = 1; k <= n - 1; k++)
  28.   {
  29.     for (c = 1; c <= space; c++)
  30.       printf(" ");
  31.  
  32.     space++;
  33.  
  34.     for (c = 1 ; c <= 2*(n-k)-1; c++)
  35.       printf("*");
  36.  
  37.     printf("\n");
  38.   }
  39.  
  40.   return 0;
  41. }

Output of program:
Diamond pattern C program output

Download Diamond program.

C program to print diamond using recursion

  1. #include <stdio.h>
  2.  
  3. void print (int);
  4.  
  5. int main () {
  6.    int rows;
  7.  
  8.    scanf("%d", &rows);
  9.  
  10.    print(rows);
  11.  
  12.    return 0;
  13. }
  14.  
  15. void print (int r) {
  16.    int c, space;
  17.    static int stars = -1;
  18.    
  19.    if (r <= 0)
  20.      return;
  21.    
  22.    space = r - 1;
  23.    stars += 2;
  24.      
  25.    for (c = 0; c < space; c++)
  26.       printf(" ");
  27.    
  28.    for (c = 0; c < stars; c++)
  29.       printf("*");
  30.    
  31.    printf("\n");
  32.    
  33.    print(--r);
  34.    
  35.    space = r + 1;
  36.    stars -= 2;
  37.    
  38.    for (c = 0; c < space; c++)
  39.       printf(" ");
  40.    
  41.    for (c = 0; c < stars; c++)
  42.       printf("*");
  43.      
  44.    printf("\n");
  45. }