C Exercises: Print a matrix in spiral form
C Array: Exercise-50 with Solution
Write a program in C to print a matrix in spiral form.
Pictorial Presentation:

Sample Solution:
C Code:
#include <stdio.h>
#define R 4
#define C 5
void spiralOfMatrix(int enrow, int encol, int arr1[R][C])
{
int i, rowind = 0, colind = 0;
while (rowind < enrow && colind < encol)
{
for (i = colind; i < encol; ++i)
{
printf("%d ", arr1[rowind][i]);
}
rowind++;
for (i = rowind; i < enrow; ++i)
{
printf("%d ", arr1[i][encol-1]);
}
encol--;
if ( rowind < enrow)
{
for (i = encol-1; i >= colind; --i)
{
printf("%d ", arr1[enrow-1][i]);
}
enrow--;
}
if (colind < encol)
{
for (i = enrow-1; i >= rowind; --i)
{
printf("%d ", arr1[i][colind]);
}
colind++;
}
}
}
int main()
{
int i,j;
int arr1[R][C] = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
//------------- print original array ------------------
printf("The given array in matrix form is : \n");
for(i = 0; i < R; i++)
{
for (j=0;j<C;j++)
{
printf("%d ", arr1[i][j]);
}
printf("\n");
}
//------------------------------------------------------
printf("The spiral form of above matrix is: \n");
spiralOfMatrix(R, C, arr1);
return 0;
}
Sample Output:
The given array in matrix form is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 The spiral form of above matrix is: 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
Flowchart:

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to find majority element of an array.
Next: Write a program in C to find the maximum circular subarray sum of a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
C Programming - What is the argument for printf that formats a long?
Put an l (lowercased letter L) directly before the specifier.
unsigned long n; long m; printf("%lu %ld", n, m);
Ref : https://bit.ly/3dIwfkP
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises