[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Cavium Networks

7. Write a program to print the matrix element in clock-wise and anti clock-wise sprial, if the given value of i=0 and i=1
Ex.
| 1 2 3 4 |
| 5 6 7 8 |
| 9 10 11 12 |
| 13 14 15 16 |
OutPut:
For i=0
1 2 3 4 8 12 16 15 14 12 9 5 6 7 11 10
for i=1
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7

Answer:

void ClockwisespiralPrint(arr[4][4], int m, int n)
{
int i = 0, k = 0, l = 0;

while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
printf(" %d ", arr[k][i]);
}
k++;

for (i = k; i < m; ++i)
{
printf(" %d ", arr[i][n-1]);
}
n--;

if ( k < m)
{
for (i = n-1; i >= l; --i)
{
printf(" %d ", arr[m-1][i]);
}
m--;
}

if (l < n)
{
for (i = m-1; i >= k; --i)
{
printf(" %d ", arr[i][l]);
}
l++;
}
}
}


int main()
{
int arr[4][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};

ClockwisespiralPrint(arr, 4, 4);
return 0;
}


For anti-clockwise reverse the operation;

Post Your Answer Here:      Public      Private

Rate This: +1 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here