Programs


Title : Program to print a matrix in spiral form

#include <stdio.h>

#define R 4

#define C 5

void spiralOfMatrix(int enrow, int encol, int arr1[R][C])

{

   int i, rowind = 0, colind = 0;

   while (rowind < enrow && colind < encol)

   {

       for (i = colind; i < encol; ++i)

       {

           printf("%d ", arr1[rowind][i]);

       }

       rowind++;

       for (i = rowind; i < enrow; ++i)

       {

           printf("%d ", arr1[i][encol - 1]);

       }

       encol--;

       if (rowind < enrow)

       {

           for (i = encol - 1; i >= colind; --i)

           {

               printf("%d ", arr1[enrow - 1][i]);

           }

           enrow--;

       }

       if (colind < encol)

       {

           for (i = enrow - 1; i >= rowind; --i)

           {

               printf("%d ", arr1[i][colind]);

           }

           colind++;

       }

   }

}

int main()

{

   int i, j;

   int arr1[R][C] = {{1, 2, 3, 4, 5},

                     {6, 7, 8, 9, 10},

                     {11, 12, 13, 14, 15},

                     {16, 17, 18, 19, 20}};

     printf("The given array in matrix form is :  \n");

   for (i = 0; i < R; i++)

   {

       for (j = 0; j < C; j++)

       {

           printf("%d  ", arr1[i][j]);

       }

       printf("\n");

   }

   printf("The spiral form of above matrix is: \n");

   spiralOfMatrix(R, C, arr1);

   return 0;

}

OUTPUT:

The given array in matrix form is : 

1  2  3  4  5 

6  7  8  9  10 

11  12  13  14  15 

16  17  18  19  20 

The spiral form of above matrix is:

1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12

Related Topics

  • Integer x appears more than n by 2 times in sorted array

      Jan 15, 2022

  • Program to find majority element of an array

      Jan 03, 2022

  • WAP to find the maximum circular sub array sum of given array

      Jan 03, 2022

  • Program to count the number of triangles from a given array

      Jan 03, 2022

  • WAP to find the number of times occurs a given number in an array

      Jan 03, 2022

  • Program to sort an array of 0s, 1s and 2s.

      Jun 30, 2021

  • Subscribe Now