C Program to Print Diamond Pattern

Introduction

This C program prints a diamond pattern based on the number of rows provided by the user. It uses nested loops to iterate through each row and column, printing spaces and asterisks accordingly.

Problem statement

Write a C program to print a diamond pattern based on the number of rows provided by the user.

C Program to Print Diamond Pattern

#include <stdio.h>

void printDiamondPattern(int n) {
    int i, j, space;
    
    // Print upper half of the diamond
    for (i = 1; i <= n; i++) {
        // Print spaces
        for (space = 1; space <= n - i; space++) {
            printf(" ");
        }
        
        // Print asterisks
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        
        printf("\n");
    }
    
    // Print lower half of the diamond
    for (i = n - 1; i >= 1; i--) {
        // Print spaces
        for (space = 1; space <= n - i; space++) {
            printf(" ");
        }
        
        // Print asterisks
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        
        printf("\n");
    }
}

int main() {
    int n;
    
    printf("Enter the number of rows (odd number): ");
    scanf("%d", &n);
    
    // Check if the number of rows is odd
    if (n % 2 == 0) {
        printf("Invalid input! Number of rows should be odd.\n");
        return 0;
    }
    
    printDiamondPattern(n);
    
    return 0;
}

How it works?

  1. The program prompts the user to enter the number of rows for the diamond pattern (should be an odd number).
  2. The input is stored in the variable n.
  3. The program checks if the number of rows is odd. If it is even, an error message is displayed and the program terminates.
  4. The function printDiamondPattern() is called with the value of n.
  5. Inside the printDiamondPattern() function, two nested loops are used to print the upper half and lower half of the diamond pattern.
  6. In each loop iteration, the appropriate number of spaces and asterisks is printed based on the current row and column.
  7. After printing all the rows, the program terminates.

Input/Output

C Program to Print Diamond Pattern

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...