C Program to Print a Diamond Pattern

1. Introduction

In this blog post, we will delve into how to create a diamond pattern using C programming. This pattern is particularly interesting because it combines ascending and descending loops to create a symmetrical shape. It's a great exercise for beginners to understand the control flow in loops and how to manipulate them to achieve complex patterns.

2. Program Steps

1. Request the number of rows for the upper half of the diamond from the user.

2. Use nested loops to print the upper half of the diamond.

3. Implement a similar logic with loops to print the lower half of the diamond, ensuring symmetry.

4. Adjust the number of spaces and stars accordingly to form the diamond shape.

3. Code Program

#include <stdio.h>

int main() {
    int n, i, j;

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

    // Printing the upper half of the diamond
    for(i = 1; i <= n; i++) {
        // Printing spaces
        for(j = i; j < n; j++) {
            printf(" ");
        }
        // Printing stars
        for(j = 1; j <= (2 * i - 1); j++) {
            printf("*");
        }
        printf("\n");
    }

    // Printing the lower half of the diamond
    for(i = n-1; i >= 1; i--) {
        // Printing spaces
        for(j = n; j > i; j--) {
            printf(" ");
        }
        // Printing stars
        for(j = 1; j <= (2 * i - 1); j++) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter the number of rows: 4
   *
  ***
 *****
*******
 *****
  ***
   *

Explanation:

1. The program starts by including the stdio.h header for input/output operations.

2. main() function initiates program execution.

3. It declares integer variables n for the number of rows, and i, j for loop counters.

4. The user is prompted to enter the number of rows for the upper half of the diamond.

5. A loop is used to print the upper half of the diamond. It increases the number of stars as it moves to new lines.

6. Spaces are printed to align the stars correctly, creating the diamond's upper half.

7. The process is reversed for the lower half of the diamond, decreasing the number of stars to complete the symmetrical shape.

8. The program completes execution by printing the diamond pattern and returning 0.


Comments