Introduction
A spiral matrix is two-dimensional. To create it, you fill the array with numbers in a spiral pattern. Starting at the top-left corner, the numbers move right, followed by down, left, and up. This process repeats until the matrix is completely filled.
Moreover, working on a spiral matrix helps you practice important C programming concepts. For instance, you’ll work with loops, conditionals, and matrix manipulation. As a result, this exercise deepens your understanding of how arrays and logic interact in C programming. Ultimately, you’ll strengthen your grasp of these core programming skills.
#include <stdio.h>
void generateSpiralMatrix(int n) {
int matrix[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int value = 1;
while (top <= bottom && left <= right) {
// Fill top row (left to right)
for (int i = left; i <= right; i++) {
matrix[top][i] = value++;
}
top++;
// Fill right column (top to bottom)
for (int i = top; i <= bottom; i++) {
matrix[i][right] = value++;
}
right--;
// Fill bottom row (right to left)
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = value++;
}
bottom--;
}
// Fill left column (bottom to top)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = value++;
}
left++;
}
}
// Print the matrix
printf("Spiral Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n;
printf("Enter the size of the matrix (n x n): ");
scanf("%d", &n);
generateSpiralMatrix(n);
return 0;
}
Input
Enter the size of the matrix (n x n): 4
Output
Spiral Matrix:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Explanation
Matrix Initialization
First, we create a 2D matrix of size n×nn \times nn×n, where each element will be assigned a value in spiral order.
Spiral Logic:
- We use four variables (
top
,bottom
,left
,right
) to track the boundaries of the matrix. - The matrix is filled by traversing the edges in a spiral order:
- First, we fill the top row (from left to right).
- Then, the right column (from top to bottom).
- After that, we fill the bottom row (from right to left).
- Finally, we fill the left column (from bottom to top).
- This process repeats until all positions in the matrix are filled.
Value Increment: The variable value
is incremented from 1 up to n2n^2n2 as we fill the matrix.
Output: After generating the matrix, the program prints the values in a neat grid format.
Conclusion
Creating a spiral matrix in C is an excellent exercise to improve your understanding of 2D arrays and loops. This algorithm efficiently fills the matrix in a spiral order and demonstrates how to control array boundaries dynamically. By modifying the size of the matrix and observing the output, you can practice handling dynamic data structures in C.