Skip to content
Related Articles

Related Articles

Improve Article

Print a matrix in alternate manner (left to right then right to left)

  • Difficulty Level : Basic
  • Last Updated : 22 Apr, 2021

Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). 
Examples: 
 

Input : arr[][2] = {{1, 2}
                    {2, 3}}; 
Output : 1  2  3  2 
 
Input :arr[][3] = { { 7 , 2 , 3 },
                    { 2 , 3 , 4 },
                    { 5 , 6 ,  1 }}; 
Output : 7  2   3  4  3  2  5  6  1

 

The solution of this problem is that run two loops and and print row in left to right and right to left manners. We maintain a flag to see if current row should be printed from left to right or right to left. We toggle the flag after every iteration.
 

C++




// C++ program to print matrix in alternate manner
#include<bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
 
// Function for print matrix in alternate manner
void convert(int arr[R][C])
{
    bool leftToRight = true;
    for (int i=0; i<R; i++)
    {
        if (leftToRight)
        {
            for (int j=0; j<C; j++)
                printf("%d ", arr[i][j]);
        }
        else
        {
            for (int j=C-1; j>=0; j--)
                printf("%d ",arr[i][j]);
        }
 
        leftToRight = !leftToRight;
    }
}
 
// Driver code
int main()
{
    int arr[][C] =
    {
        { 1 , 2 , 3 },
        { 3 , 2 , 1 },
        { 4 , 5 , 6 },
    };
 
    convert(arr);
    return 0;
}

Java




//Java program to print matrix in alternate manner
class GFG {
 
    static final int R = 3;
    static final int C = 3;
 
// Function for print matrix in alternate manner
    static void convert(int arr[][]) {
        boolean leftToRight = true;
        for (int i = 0; i < R; i++) {
            if (leftToRight) {
                for (int j = 0; j < C; j++) {
                    System.out.printf("%d ", arr[i][j]);
                }
            } else {
                for (int j = C - 1; j >= 0; j--) {
                    System.out.printf("%d ", arr[i][j]);
                }
            }
 
            leftToRight = !leftToRight;
        }
    }
 
// Driver code
    static public void main(String[] args) {
        int arr[][]
                = {
                    {1, 2, 3},
                    {3, 2, 1},
                    {4, 5, 6},};
 
        convert(arr);
    }
}
 
// This code is contributed by Rajput-Ji

Python 3




# Python 3 program to print matrix
# in alternate manner
R = 3
C = 3
 
# Function for print matrix
# in alternate manner
def convert(arr):
 
    leftToRight = True
    for i in range(R):
        if (leftToRight):
            for j in range(C):
                print(arr[i][j], end = " ")
     
        else:
            for j in range(C - 1, -1, -1):
                print(arr[i][j], end = " ")
 
        leftToRight = not leftToRight
 
# Driver code
if __name__ == "__main__":
    arr =[[ 1 , 2 , 3 ],
          [ 3 , 2 , 1 ],
          [ 4 , 5 , 6 ]]
 
    convert(arr)
 
# This code is contributed
# by ChitraNayal

C#




     
//C# program to print matrix in alternate manner
using System;
public class GFG {
  
    static readonly int R = 3;
    static readonly int C = 3;
  
// Function for print matrix in alternate manner
    static void convert(int [,]arr) {
        bool leftToRight = true;
        for (int i = 0; i < R; i++) {
            if (leftToRight) {
                for (int j = 0; j < C; j++) {
                    Console.Write(arr[i,j]+" ");
                }
            } else {
                for (int j = C - 1; j >= 0; j--) {
                    Console.Write(arr[i,j]+" ");
                }
            }
  
            leftToRight = !leftToRight;
        }
    }
  
// Driver code
    static public void Main() {
        int [,]arr
                = {
                    {1, 2, 3},
                    {3, 2, 1},
                    {4, 5, 6},};
  
        convert(arr);
    }
}
  
// This code is contributed by Rajput-Ji

PHP




<?php
// PHP program to print matrix
// in alternate manner
$R = 3;
$C = 3;
 
// Function for print matrix
// in alternate manner
function convert($arr)
{
    global $R;
    global $C;
    $leftToRight = true;
    for ($i = 0; $i < $R; $i++)
    {
        if ($leftToRight)
        {
            for ($j = 0; $j < $C; $j++)
                echo $arr[$i][$j], " ";
        }
        else
        {
            for ($j = $C - 1; $j >= 0; $j--)
                echo $arr[$i][$j], " ";
        }
 
        $leftToRight = !$leftToRight;
    }
}
 
// Driver code
$arr = array(array(1 , 2 , 3 ),
             array(3 , 2 , 1 ),
             array(4 , 5 , 6 ));
 
convert($arr);
 
// This code is contributed by ajit
?>

Javascript




<script>
// Javascript program to print matrix in alternate manner
    let R = 3;
    let C = 3;
     
    // Function for print matrix in alternate manner
    function convert(arr)
    {
        let leftToRight = true;
        for (let i = 0; i < R; i++) {
            if (leftToRight) {
                for (let j = 0; j < C; j++) {
                    document.write(arr[i][j]+" ");
                }
            } else {
                for (let j = C - 1; j >= 0; j--) {
                    document.write( arr[i][j]+" ");
                }
            }
   
            leftToRight = !leftToRight;
        }
    }
     
    // Driver code
    let arr =[[ 1 , 2 , 3 ],
          [ 3 , 2 , 1 ],
          [ 4 , 5 , 6 ]]
    convert(arr)
     
    // This code is contributed by avanitrachhadiya2155
</script>

Output: 
 

1 2 3 1 2 3 4 5 6

Time Complexity : O(R*C) 
Space Complexity : O(1)
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :