C PROGRAM TO PRINT MATRIX IN SNAIL SHELL WAY
/** C PROGRAM TO PRINT MATRIX IN SNAIL SHELL FORMAT **/
//for printing matrix as in the below given format
// 01 02 03 04
// 12 13 14 05
// 11 16 15 06
// 10 09 08 07
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
#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 the size of matrix { printf("\n Size of matrix should not more than 15"); getch(); return; } for(i=0;i<size;i++) { for(j=0;j<size;j++) { // initializing all the elements to zero arr[i][j]=0; } } //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) { // for numbers less than zero printing in 01,02 etc.. format printf("\t0%d",arr[i][j]); } else { printf("\t%d",arr[i][j]); } if(j==size-1) { printf("\n\n"); } } } printf("\t"); for(i=0;i<size;i++) { //printing outline for matrix printf("-------"); } printf("\n"); // getch(); } |
Output: ( using GNU GCC Compiler with code::blocks IDE, hence no need of clrscr(); and getch(); so we are commenting that )