Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
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
iby 2 each iteration to generate consecutive pairs - Variable
kdetermines 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.
Advertisements
