C program to print diamond pattern of numbers

Here's a program to print a simple diamond pattern of numbers:

#include <stdio.h>

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

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

    for (i = 1; i <= n; i++) {
        // Print spaces before the numbers
        for (space = 1; space <= n - i; space++) {
            printf("  ");
        }

        // Print ascending numbers
        for (j = 1, number = 1; j <= 2 * i - 1; j++, number++) {
            printf("%2d", number);
        }

        printf("\n");
    }

    for (i = n - 1; i >= 1; i--) {
        // Print spaces before the numbers
        for (space = 1; space <= n - i; space++) {
            printf("  ");
        }

        // Print ascending numbers
        for (j = 1, number = 1; j <= 2 * i - 1; j++, number++) {
            printf("%2d", number);
        }

        printf("\n");
    }

    return 0;

This program will create a diamond pattern of numbers based on the number of rows you input. It prints ascending numbers in the top half and descending numbers in the bottom half.

For example, if you input 5 for the number of rows, the program will generate the following diamond pattern:

    1
   123
  12345
 1234567
123456789
 1234567
  12345
   123
    1 

You can adjust the number of rows by changing the value you enter when prompted.

 

Prasun Barua

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other published books are Solar PV System Design and Technology, Electricity from Renewable Energy, Tech Know Solar PV System, C Coding Practice, AI and Robotics Overview, Robotics and Artificial Intelligence, Know How Solar PV System, Know The Product, Solar PV Technology Overview, Home Appliances Overview, Tech Know Solar PV System, C Programming Practice, etc. These books are available at Google Books, Google Play, Amazon and other platforms.

*

Post a Comment (0)
Previous Post Next Post