Print a matrix in snake pattern from first column
C program to print a matrix in snake pattern from first column.
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_snake(int mat[MAX][MAX], int row, int col)
{
int i, j, dir;
j = 0;
dir = 1; //wave direction left to right, 0 for right to left
while(j < row)
{
if(dir == 1)
{
for(i=0;i<col;i++)
{
printf("%d ",mat[j][i]);
}
dir = 0;
j++;
}
else
{
for(i=col-1;i>=0;i--)
{
printf("%d ",mat[j][i]);
}
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 snake form is \n");
print_snake(mat, row, col);
getch();
}
Output
Enter the number of rows :5
Enter the number of columns :5
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 [1][0] :6
Element [1][1] :7
Element [1][2] :8
Element [1][3] :9
Element [1][4] :10
Element [2][0] :11
Element [2][1] :12
Element [2][2] :13
Element [2][3] :14
Element [2][4] :15
Element [3][0] :16
Element [3][1] :17
Element [3][2] :18
Element [3][3] :19
Element [3][4] :20
Element [4][0] :21
Element [4][1] :22
Element [4][2] :23
Element [4][3] :24
Element [4][4] :25
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 25
Matrix in snake form is
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 21 22 23 24 25