Interview Questions

Print the M*N matrix in spiral manner.

Microsoft Interview Questions and Answers


(Continued from previous question...)

47. Print the M*N matrix in spiral manner.

Question:
Print the M*N matrix in spiral manner.


maybe an answer:

#include<stdio.h>
#include<string.h>

main()
{
int m,n,i,j,left,right,top,down;
printf ("enter m : ");
scanf("%d",&m);
printf ("enter n : ");
scanf("%d",&n);
int **a;
a=(int**)malloc(m*sizeof(int*));
for (i=0;i<m;i++)
a[i]=(int*)malloc(n*sizeof(int));

printf ("enter the elements of matrix one by one (press enter after each one)\n");

for (i=0;i<m;i++)
{ for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
}

printf ("you have entered the matrix\n");
for (i=0;i<m;i++)
{ for (j=0;j<n;j++)
printf("%6d ",a[i][j]);
printf ("\n");
}

left=0;
right=n;
top=0;
down=m;

printf ("\n");
printf ("The spiral form is : ");
printf ("\n");

while (1)
{

for (j=left;j<right;j++)
printf ("%d ",a[top][j]);
top++;
if (left>right-1 || top>down-1)
break;

for (i=top;i<down;i++)
printf ("%d ",a[i][right-1]);
right--;
if (left>right-1 || top>down-1)
break;

for (j=right-1;j>=left;j--)
printf ("%d ",a[down-1][j]);
down--;
if (left>right-1 || top>down-1)
break;

for (i=down-1;i>=top;i--)
printf ("%d ",a[i][left]);
left++;
if (left>right-1 || top>down-1)
break;

}
printf ("\n");
}



maybe an answer2:

SM()
i1 = 0, i2 = n, j1 = 0, j2 = m
i = 0, j=0
while(i2 >=n/2 || j2 >= m/2 || i1 < n/2 || i2 <=n/2)
for each j from j1 to j2
print a[i][j]
i1 = i1+1
j = j2

for each i from i1 to i2
print a[i][j]
j2 = j2-1
i = i2

for each j from j2 to j1
print a[i][j]
i2 = i2-1
j = j1

for each i from i2 to i1
print a[i][j]
j1 = j1 +1
i = i1

(Continued on next question...)

Other Interview Questions