Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to print a matrix in snake pattern.

Write a program to print a matrix in snake pattern.

Given a matrix, we have to print the matrix in snake pattern. and print the resultant matrix in snake pattern.

Example:

Input:1 2 3 4 5 6
Output:1 2 3 6 5 4 

Logic:

STEP 1: if the row is even then print element from left to right.
STEP 2:if the row is odd then print element from right to left.

Code

#include<bits/stdc++.h>
using namespace std;
int main() 
{
int m,n,i,j;
  cin>>m>>n;
  int a[m][n];
 for(int i=0;i<m;i++)
 {
     for(int j=0;j<n;j++)
     {
         cin>>a[i][j];
     }
 }
   for (i = 0; i < m; i++)
   { 
      if (i % 2 == 0)
      {
         for (j = 0; j < n; j++) 
         {
          cout<<a[i][j]<<" ";
         }
      }
      else
      {
         for (j = n - 1; j >= 0; j--)
         {
           cout<<a[i][j]<<" ";
         }
      }
   }
   
  
}

Ouput:

input:
2 3
1 2 3 4 5 6

output:
1 2 3 6 5 4 

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments