Print 2-D array in spiral order

#include <stdio.h>
int main() {
int arr[3][3]= {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9},
            };
       spiral(arr); 
  return 0;
}
void spiral(int arr[3][3])
{
    int top =0,right=2,left=0,bottom=2,dir =1, i;
   
    while(top <= bottom && left <= right)
    {
        if (dir==1)
        {
            for( i =0;i<=2;++i)
            {
                printf("%d",arr[top][i]);
            }
              ++top;
              dir=2;
        }
       
        else if(dir==2)
        {
            for(i = top;i<=2;++i)
            {
              printf("%d",arr[i][right]);
            }
            --right;
             dir=3;
        }
       
        else if(dir==3)
        {
            for(i=top;i>=left;--i)
            {
              printf("%d",arr[bottom][i]);
            }
            --bottom;
            dir=4;
        }
       
        else if(dir==4)
        {
          for(i=bottom;i>=top;--i)
          {
            printf("%d",arr[i][left]);
          }
          ++left;
        dir =1;
        }
                   
    }
        }

Expected Output:
123698745


Comments

Popular posts from this blog

Finding the second largest in an array