Program in C to Print Diamond Pattern

Program in C to Print Diamond Pattern

A diamond pattern is a combination of a normal pyramid and an inverted pyramid. The top half forms a pyramid, and the bottom half forms an inverted pyramid, creating a symmetrical diamond shape. Printing such patterns helps in understanding nested loops and control of spaces and stars in C.

Understanding The Problem

The program should take the number of rows for the top half of the diamond and print a complete diamond of stars. Proper management of spaces and stars in each half is crucial for symmetry. Nested loops are used to control rows, spaces, and stars.

Steps to Solve the Problem:

  • Take the number of rows for the upper half as input.
  • Print the top half of the diamond using nested loops.
  • Print the bottom half (inverted pyramid) using nested loops.
  • Ensure proper spacing for symmetry.

Solution: Using Nested Loops

Nested loops are used to print spaces followed by stars in both halves of the diamond.

#include <stdio.h>

int main() {

    int rows;

    printf("Enter number of rows for the top half: ");
    scanf("%d", &rows);

    // Top half of diamond
    for(int i = 1; i <= rows; i++) {

        // Print spaces
        for(int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print stars
        for(int k = 1; k <= (2 * i - 1); k++) {
            printf("*");
        }

        printf("\n");

    }

    // Bottom half of diamond
    for(int i = rows - 1; i >= 1; i--) {

        // Print spaces
        for(int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print stars
        for(int k = 1; k <= (2 * i - 1); k++) {
            printf("*");
        }

        printf("\n");

    }

    return 0;

}

The program prints the top half using increasing rows of stars and spaces. The bottom half is printed using decreasing rows of stars, forming a symmetrical diamond. The expression (2 * i - 1) ensures the correct number of stars per row.

Diamond Pattern

FAQs

Q1: Can this diamond use a different character instead of *?
Yes, you can replace * with any symbol to create a diamond with that character.

Q2: Can the number of rows be decimal?
No, the number of rows must be an integer for proper symmetry.

Q3: Can we create a hollow diamond?
Yes, by printing spaces inside the diamond and only printing stars on the edges, you can create a hollow diamond.

Conclusion

This program demonstrates how to print a diamond pattern using nested loops. By combining a normal pyramid and an inverted pyramid, you can create a symmetrical pattern. This concept can be extended to hollow diamonds, numeric diamonds, or patterns with different symbols.

References & Additional Resources

Scroll to Top