Print a matrix in wave form
C program to print a matrix in wave form.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void print_wave(int mat[MAX][MAX], int row, int col)
{
int i, j, dir;
j = 0;
dir = 1; //wave direction down, 0 for up
while(j < col)
{
if(dir == 1)
{
for(i=0;i<row;i++)
{
printf("%d ",mat[i][j]);
}
dir = 0;
j++;
}
else
{
for(i=row-1;i>=0;i--)
{
printf("%d ",mat[i][j]);
}
dir = 1;
j++;
}
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
printf("\nMatrix in wave form is \n");
print_wave(mat, row, col);
getch();
}
Output
Enter the number of rows :4
Enter the number of columns :6
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [0][4] :5
Element [0][5] :6
Element [1][0] :7
Element [1][1] :8
Element [1][2] :9
Element [1][3] :10
Element [1][4] :11
Element [1][5] :12
Element [2][0] :13
Element [2][1] :14
Element [2][2] :15
Element [2][3] :16
Element [2][4] :17
Element [2][5] :18
Element [3][0] :19
Element [3][1] :20
Element [3][2] :21
Element [3][3] :22
Element [3][4] :23
Element [3][5] :24
Matrix entered is
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
Matrix in wave form is
1 7 13 19 20 14 8 2 3 9 15 21 22 16 10 4 5 11 17 23 24 18 12 6