C Online Compiler
Example: Print Matrix in Spiral Form in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Print Matrix in Spiral Form #include <stdio.h> void printMatrixInSpiral(int rows, int cols, int matrix[rows][cols]) { int top = 0; // Top row index int bottom = rows - 1; // Bottom row index int left = 0; // Left column index int right = cols - 1; // Right column index // Loop until all elements are processed while (top <= bottom && left <= right) { // Step 1: Print the top row from left to right for (int i = left; i <= right; i++) { printf("%d ", matrix[top][i]); } top++; // Move top boundary down // Step 2: Print the rightmost column from top to bottom for (int i = top; i <= bottom; i++) { printf("%d ", matrix[i][right]); } right--; // Move right boundary left // Step 3: Print the bottom row from right to left, if bottom boundary is still valid if (top <= bottom) { // Check needed for single row or already processed row for (int i = right; i >= left; i--) { printf("%d ", matrix[bottom][i]); } bottom--; // Move bottom boundary up } // Step 4: Print the leftmost column from bottom to top, if left boundary is still valid if (left <= right) { // Check needed for single column or already processed column for (int i = bottom; i >= top; i--) { printf("%d ", matrix[i][left]); } left++; // Move left boundary right } } printf("\n"); // Newline after printing } int main() { // Example 1: 3x4 Matrix int matrix1[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; printf("Matrix 1 (3x4) in spiral form: "); printMatrixInSpiral(3, 4, matrix1); // Example 2: 4x4 Matrix int matrix2[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; printf("Matrix 2 (4x4) in spiral form: "); printMatrixInSpiral(4, 4, matrix2); // Example 3: Single row matrix int matrix3[1][5] = { {10, 20, 30, 40, 50} }; printf("Matrix 3 (1x5) in spiral form: "); printMatrixInSpiral(1, 5, matrix3); // Example 4: Single column matrix int matrix4[5][1] = { {10}, {20}, {30}, {40}, {50} }; printf("Matrix 4 (5x1) in spiral form: "); printMatrixInSpiral(5, 1, matrix4); return 0; }
Output
Clear
ADVERTISEMENTS