/**C PROGRAM TO PRINT A MULTI-DIMENSIONAL ARRAY IN SNAIL SHELL WAY**/
//for printing matrix as in the below given format
// 1 2 3 4
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
#include<stdio.h>
//#include<conio.h>
#define rows 15
#define cols 15
main()
{
int arr[rows][cols],i,j,k,size,count=0,a=0,b=1;
// clrscr();
printf("\n Enter the size of Square Matrix(for ex:5) :");
scanf("%d",&size);
if(size>15) //limiting tye size of matrix
{
printf("\n Size of matrix should not nore than 15");
getch();
return;
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
arr[i][j]=0;
// initializing all the elements to zero
}
}
//loop starts here for performing actions
//to get the required format
for(k=1;k<size;k++,a++)
{
for(i=a,j=a;j<size-k;j++)
{
arr[i][j]=++count;
}
for(i=a,j=size-k;i<size-k;i++)
{
arr[i][j]=++count;
}
for(i=size-k,j=size-k;j>=a;j--)
{
arr[i][j]=++count;
}
for(i=size-(k+1),j=a;i>=k;i--)
{
arr[i][j]=++count;
}
} //loop ends here
printf("\n\n\t****** %d X %d MATRIX ******",size,size);
printf("\n\n\n");
printf("\t");
for(i=0;i<size;i++) { printf("-------"); } printf("\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(arr[i][j]<10)
{
printf("\t0%d",arr[i][j]);
// for numbers less than zero printing in 01,02 etc.. format
}
else
{
printf("\t%d",arr[i][j]);
}
if(j==size-1)
{
printf("\n\n");
}
}
}
printf("\t");
for(i=0;i<size;i++) { printf("-------"); } printf("\n"); //printing outline for matrix
// getch();
}
Output: ( using GNU GCC Compiler with code::blocks IDE, hence no need of clrscr(); and getch(); so we are commenting that )
Other Links :
C# PROGRAM PRINT A MULTI-DIMENSIONAL ARRAY IN SNAIL SHELL WAY
No comments:
Post a Comment