C Program for diamond pattern with different layers

A diamond pattern in C is a symmetric arrangement of numbers that forms a diamond shape. The pattern starts with a single digit at the top, expands to show increasing sequences in the middle, and then contracts back to a single digit at the bottom.

Syntax

void print_pattern(int n);

Approach

The algorithm for creating a diamond pattern with n layers follows these steps −

  • The pattern has (2 * n + 1) total rows
  • First and last rows contain only "0" with proper spacing
  • For rows 1 to n-1: numbers increase from 0 to row_number and back to 0
  • Middle row (row n): numbers go from 0 to n and back to 0
  • For rows n+1 to 2n-1: numbers decrease symmetrically

Example

Here's a complete C program to generate a diamond pattern with n=3 layers −

#include <stdio.h>

void print_pattern(int n) {
    int i, j;
    
    // Print first row (top of diamond)
    for (i = 1; i <= n * 2; i++)
        printf(" ");
    printf("0<br>");
    
    // Print expanding part (rows 1 to n-1) and middle row
    for (i = 1; i <= n; i++) {
        // Print leading spaces
        for (j = 1; j <= (n - i) * 2; j++)
            printf(" ");
        
        // Print ascending numbers
        for (j = 0; j <= i; j++)
            printf("%d ", j);
        
        // Print descending numbers
        for (j = i - 1; j > 0; j--)
            printf("%d ", j);
        
        printf("0<br>");
    }
    
    // Print contracting part (rows n+1 to 2n-1)
    for (i = n - 1; i >= 1; i--) {
        // Print leading spaces
        for (j = 1; j <= (n - i) * 2; j++)
            printf(" ");
        
        // Print ascending numbers
        for (j = 0; j <= i; j++)
            printf("%d ", j);
        
        // Print descending numbers
        for (j = i - 1; j > 0; j--)
            printf("%d ", j);
        
        printf("0<br>");
    }
    
    // Print last row (bottom of diamond)
    for (i = 1; i <= n * 2; i++)
        printf(" ");
    printf("0");
}

int main() {
    int n = 3;
    printf("Diamond pattern with %d layers:<br>", n);
    print_pattern(n);
    return 0;
}
Diamond pattern with 3 layers:
      0
    0 1 0
  0 1 2 1 0
0 1 2 3 2 1 0
  0 1 2 1 0
    0 1 0
      0

How It Works

The pattern formation logic −

  • Spacing calculation: Leading spaces = (n - current_level) * 2
  • Number sequence: Ascending from 0 to current_level, then descending back to 0
  • Symmetry: The bottom half mirrors the top half (excluding middle row)

Conclusion

The diamond pattern demonstrates nested loops and symmetric number arrangement in C. The key is calculating proper spacing and understanding the ascending-descending number sequence for each row.

Updated on: 2026-03-15T12:15:55+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements