Saturday, 24 June 2017

C Program to traverse a matrix in spiral order

C Program to traverse a matrix in spiral order is given below. The program is compiled and checked successfully output is also given below the program.

Example:

A[4][4]= {  1 , 2 , 3 , 4
                   5 , 6 , 7 , 8
                   9 , 10 , 11 , 12
                  13 , 14 , 15 , 16  }

Spiral traversal:    1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10

PROGRAM:

#include<iostream>
using namespace std;
#define M 10
#define N 10

void spiral(int arr[M][N],int m,int n){


    int startrow=0,startcol=0,endrow=n-1,endcol=m-1;

    while(startrow<=endrow && startcol<=endcol)
    {
 
        for(int i=startcol;i<=endcol;i++){
            cout<<arr[startrow][i]<<" ";
        }
        startrow++;

        for(int i=startrow;i<=endrow;i++){
            cout<<arr[i][endcol]<<" ";
        }
        endcol--;

        if(startrow<=endrow){
            for(int i=endcol;i>=startcol;i--){
                cout<<arr[endrow][i]<<" ";
            }
            endrow--;
        }

        if(startcol<=endcol){
            for(int i=endrow;i>=startrow;i--){
                cout<<arr[i][startcol]<<" ";
            }
            startcol++;
        }
    }
}

int main(){
    
    
  

       int m,n;

       cout<<"\nEnter the number or rows and column of the matrix: \n";
       cin>>m>>n;
       int arr[M][N];

       cout<<"\n\nEnter the elements of the matrix: \n\n";
       for(int i=0;i<m;i++)
       {

          for(int j=0;j<n;j++)
          {
            cin>>arr[i][j];
          }
       }
      
      cout<<"\n\nThe spiral traversal of matrix is: \n\n";
      spiral(arr,m,n);
      cout<<"\n";
     
   
     return 0;
}



OUTPUT:





EmoticonEmoticon