Write a c program to print a given matrix in wave format. for example give a matrix like below.

int m[][5]={         {1,2,3,4,5},
                     {6,5,5,6,7},
                     {4,6,8,8,9},
                     {7,7,7,6,8}};

The output should be  1 6 4 7 7 6 5 2 3 5 8 7 6 8 6 4 5 7 9 8.

Strategy to solve this problem>

    (1) select first column and print from top to bottom

    (2) select second column and print from bottom to up

    (3) continue these alternate steps until last column.

#include<stdio.h>

#define row 4
#define col 5

void makeWave( int m[][5],int r, int c);

int main ()
{
  /* input matrix */

  int m[][5] = {
  {1, 2, 3, 4, 5},
  {6, 5, 5, 6, 7},
  {4, 6, 8, 8, 9},
  {7, 7, 7, 6, 8}
  };

  // expected out put
  // 1 6 4 7 7 6 5 2 3 5 8 7 6 8 6 4 5 7 9 8
 
  /* call makeWave */
  makeWave(m, row,col);
  printf("\n");
}
void makeWave( int m[][5],int r, int c)
{
    int i=0;
        int j=0;
        int dir=0; // 0 down direction
                   // 1 up direction
        while( j < col )  
        {
                if( dir == 0)
        {
            for(i=0;i< r;i++)       // print top to down
            printf("%d ",m[i][j]);
                dir=1;
                j++;
        }
        else
        {   // print buttom to up
                    for(i=row -1; i>=0;i--)
            printf("%d ",m[i][j]);

                j++;
                dir=0;     
        }
               
         }
    
}



Related Contents to follow