C Program to Print Diamond Patterns.

In this C programming tutorial, we will explore how to print diamond patterns using loops. 


The diamond pattern consists of two inverted right-angled triangles joined at the base. These patterns are a classic example of nested loops, where we use loops inside loops to control the pattern's structure.


Here we are going to print two different types of Diamond Patterns:

Pattern 1: Diamond Pattern with Asterisks.

C Code:

//C program to print diamond patterns
#include <stdio.h>

int main() {
    int rows, i, j, space;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Upper half of the diamond
    for (i = 1; i <= rows; i++) {
        for (space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        printf("\n");
    }

    // Lower half of the diamond
    for (i = rows - 1; i >= 1; i--) {
        for (space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
Output:
Enter the number of rows: 7
      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *

Pattern 2: Hollow Diamond Pattern.

C Code:

// C program to print hollow diamond shape
#include <stdio.h>

int main() {
    int rows, i, j, space;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Upper half of the diamond
    for (i = 1; i <= rows; i++) {
        for (space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            if (j == 1 || j == 2 * i - 1) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }

    // Lower half of the diamond
    for (i = rows - 1; i >= 1; i--) {
        for (space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            if (j == 1 || j == 2 * i - 1) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}
Output:
Enter the number of rows: 6
     *
    * *
   *   *
  *     *
 *       *
*         *
 *       *
  *     *
   *   *
    * *
     *

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS