Home » Print the diamond pattern using recursion in C

Print the diamond pattern using recursion in C

Learn about Print the diamond pattern using recursion in C in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

Contents

Print the diamond pattern using recursion in C

To print a diamond star pattern as below use the below C code. The code follows a recursive approach to print the following pattern.

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

Program:

 #include<stdio.h> 
 void printDiamond (int r)
 {
    int c, space;
    static int stars = -1;

    if (r <= 0) return;
    space = r - 1;
    stars += 2;
    for (c = 0; c < space; c++)
    printf(" ");
    for (c = 0; c < stars; c++)
    printf("*");
    printf("\n");

    printDiamond(--r);
    space = r + 1;
    stars -= 2;
    for (c = 0; c < space; c++)
    printf(" ");
    for (c = 0; c < stars; c++)
    printf("*");
    printf("\n"); //next line
 }

 int main ()
 {
   int n;

   printf("Enter number of rows: ");
   scanf("%d",&n);

   printDiamond(n);

   return 0;
 }

Output:

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

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
C Program to Print Diamond Star Pattern
Half Diamond Pattern Programs Using Numbers in C