C Program to Print a Diamond Shape with Numbers

1. Introduction

Printing patterns is a classic exercise in learning programming, and creating a diamond shape with numbers adds an interesting twist to this task. This type of pattern not only helps in understanding nested loops but also in manipulating them to display numbers in a creative way. In this tutorial, we will develop a C program that prints a diamond shape filled with numbers.

2. Program Steps

1. Prompt the user to enter the number of rows for the upper half of the diamond.

2. Use nested loops to print the upper half of the diamond, incrementing numbers row-wise.

3. Implement a similar strategy to print the lower half of the diamond, decrementing the row numbers.

4. Ensure the numbers are aligned properly to form a diamond shape.

3. Code Program

#include <stdio.h>

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

    // User input for the number of rows for the upper half of the diamond
    printf("Enter the number of rows: ");
    scanf("%d", &n);

    // Printing the upper half of the diamond
    for(i = 1; i <= n; i++) {
        // Print leading spaces
        for(j = i; j < n; j++) {
            printf(" ");
        }
        // Print numbers
        for(k = 1; k <= (2 * i - 1); k++) {
            printf("%d", k);
        }
        printf("\n");
    }

    // Printing the lower half of the diamond
    for(i = n - 1; i >= 1; i--) {
        // Print leading spaces
        for(j = n; j > i; j--) {
            printf(" ");
        }
        // Print numbers
        for(k = 1; k <= (2 * i - 1); k++) {
            printf("%d", k);
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter the number of rows: 4
   1
  123
 12345
1234567
 12345
  123
   1

Explanation:

1. The program includes the stdio.h header for input and output functions.

2. It begins by declaring integer variables n (for the number of rows), i, j (for loops), and k (for printing numbers).

3. The user is prompted to enter the number of rows, which determines the size of the diamond's upper half.

4. The first loop iterates to print the upper half of the diamond. Inside this loop, another loop prints spaces to align the numbers correctly, and a subsequent loop prints the numbers from 1 to (2 * i - 1) for each row.

5. After printing the upper half, a similar loop structure is used to print the lower half of the diamond, but in reverse order, decreasing the number of printed numbers in each row.

6. Leading spaces are printed to maintain the diamond shape, followed by the numbers, creating a symmetric diamond pattern.

7. The program concludes with return 0;, indicating successful completion.


Comments