In C programming how can I return all numbers of a matrix in spiral order like m
ID: 3674468 • Letter: I
Question
In C programming how can I return all numbers of a matrix in spiral order like my hw has asked?
2. Spiral matrix Given a matrix of m x n elements (mrows, n columns), return all elements of the matrix in spiral order. For example Given the following matrix 1, 2, 3j. I 1,2,3] 4,5,61 [7, 8, 9 1] You should output 1,2,3,6,9,8,7,4,5 Hint: First you need to initialize the matrix row by row. The rule is increasing 1 from left to right. Then the next row's first element would be larger than previous row's last element, like the example above After that, you need to print the matrix spirally. The algorithm is actually simple, you have four variables: int left = 0, right = N-1, top = 0, bottom = M-1 by row. The rule is ac The row's first element wouldan then you need four for loops to print it (1) from left to right, print the top row, then top (2) from top to bottom print the right column, then right- (3) from right to left, print the bottom row, then bottom+ 4) from bottom to top, print the left column, then leftt You stop the loop when either left right or top bottom Output all numbers in one line separated by a comma.Explanation / Answer
Program:
#include <stdio.h>
#define R 3
#define C 6
void spiralPrint(int m, int n, int a[R][C])
{
int i, k = 0, l = 0;
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
printf("%d ", a[k][i]);
}
k++;
for (i = k; i < m; ++i)
{
printf("%d ", a[i][n-1]);
}
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
printf("%d ", a[m-1][i]);
}
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
{
printf("%d ", a[i][l]);
}
l++;
}
}
}
int main()
{
int a[R][C] = {1,2,3},
{4,5,6},
{7,8,9}
};
spiralPrint(R, C, a);
return 0;
}