Total Pageviews

Thursday 14 March 2013

Program which prints the matrix elements in a spiral fashion!!!


#include<stdio.h>

int main()
{
    int **a,n,i,j,start=0,size,count=0,sizz;
    printf("enter the size\n");  //enter the size of nXn matrix
    scanf("%d",&n);
    //dynamic memory allocation of 2-D array
    a=(int**)malloc(sizeof(int*)*n);
    for(i=0;i<n;i++)
    {
                    a[i]=(int*)malloc(sizeof(int)*size);
    }
    //Storing the values from 1 in ascending order in the array
    for(i=0;i<n;i++)
    {
                    for(j=0;j<n;j++)
                    {
                                    a[i][j]=i*n+j+1;
                    }
    }
    printf("Matrix is...\n");
    for(i=0;i<n;i++)
    {
                    for(j=0;j<n;j++)
                    {
                                    printf("%d\t",a[i][j]);
                    }
                    printf("\n");
    }
   
    i=0;j=0;sizz=n*n;
    n--;
    printf("Spiral output of a matrix.....\n")
    while(count<sizz)     //loop until all the elements are printed
    {
                   //printing from left to right

                   while(j<=n && count<sizz)  
                   {
                                 printf("%d",a[i][j]);
                                 j++;
                                 count++;
                   }
                   i++;
                   j--;
                 
                   //printing from right to left

                   while(i<=n && count<sizz)
                   {
                                  printf("%d",a[i][j]);
                                  i++;
                                  count++;
                   }
                   i--;
                   j--;
                   n--;
                 
                   //printing from top to bottom

                   while(j>=start && count<sizz)
                   {
                          printf("%d",a[i][j]);
                          j--;
                          count++;
                   }
                   i--;
                   j++;
                   start++;
                 
                   //printing from bottom to top

                   while(i>=start && count<sizz)
                   {
                           printf("%d",a[i][j]);
                           i--;
                           count++;
                   }
                   i++;
                   j++;          
    }      
   
    getch();
    return 0;
}

OUTPUT:

enter the size
5

Matrix is...
1       2       3       4
5       6       7       8
9       10     11     12
13     14     15     16

Spiral output of a matrix.....
1       2       3       4       8       12      16      15      14      13
9       5       6       7       11      10




No comments:

Post a Comment