C program to represent the numbers in spiral pattern

In C programming, a spiral pattern displays numbers in alternating left-to-right and right-to-left order across rows. This creates a visual spiral effect where consecutive pairs of numbers appear in different orders on each row.

Spiral Pattern 1 2 4 3 5 6 8 7 Blue: Left to Right Red: Right to Left Pattern alternates every row

Syntax

for(i=1; i<=rows*2; i+=2) {
    if(k%2 == 1) {
        printf("%3d %3d", i, i+1);    // Left to right
    } else {
        printf("%3d %3d", i+1, i);    // Right to left
    }
}

How It Works

The algorithm uses a counter k to track row numbers. When k is odd, numbers are printed left-to-right. When k is even, they're printed right-to-left, creating the spiral effect.

Example

Following is the C program for representing numbers in spiral pattern −

#include <stdio.h>

int main() {
    int i, rows, k = 1;
    
    printf("Enter number of Rows for Spiral Pattern: ");
    scanf("%d", &rows);
    
    for(i = 1; i <= rows * 2; i += 2) {
        if(k % 2 == 1) {
            printf("%3d %3d", i, i + 1);
            k++;
        } else {
            printf("%3d %3d", i + 1, i);
            k++;
        }
        printf("<br>");
    }
    
    return 0;
}

Output

Enter number of Rows for Spiral Pattern: 5
  1   2
  4   3
  5   6
  8   7
  9  10

Key Points

  • The loop increments i by 2 each iteration to generate consecutive pairs
  • Variable k determines the printing order for each row
  • The pattern creates a visual spiral effect with alternating directions

Conclusion

The spiral pattern program demonstrates how simple conditional logic can create interesting visual patterns. By alternating the order of number pairs based on row position, we achieve an elegant spiral arrangement.

Updated on: 2026-03-15T14:07:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements