# Print a given matrix in zigzag form

Given a 2D array, print it in zigzag form.
Examples :

```Input :
1    2   3   4   5
6    7   8   9   10
11   12  13  14  15
16  17  18  19   20
Output :
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16

Input :
10    24   32
50    6    17
99    10   11

Output :
10 24 32 17 6 50 99 10 11
```

## C++

`// C++ program to print `
`// matrix in zig-zag form `
`#include <iostream> `
`using` `namespace` `std; `
` `
`    ``// Method to print matrix in zig-zag form `
`    ``void` `printZigZag(``int` `row, ``int` `col, ``int` `a[][5]) `
`    ``{ `
`        ``int` `evenRow = 0; ``//starts from the first row `
`        ``int` `oddRow = 1; ``//starts from the next row `
` `
`        ``while` `(evenRow<row)  `
`        ``{ `
`            ``for` `(``int` `i=0;i<col;i++) `
`            ``{ `
`                ``// evenRow will be printed `
`                        ``// in the same direction `
`                ``cout<<a[evenRow][i] << ``" "``;  `
`            ``} `
`             `
`            ``// Skipping next row so as `
`                ``// to get the next evenRow `
`            ``evenRow = evenRow + 2;  `
`             `
`            ``if``(oddRow < row) `
`            ``{ `
`                ``for` `(``int` `i=col-1; i>=0; i--) `
`                ``{ `
`                ``// oddRow will be printed in `
`                    ``// the opposite direction `
`                ``cout<<a[oddRow][i] << ``" "``;  `
`                ``} `
`            ``} `
`         `
`            ``// Skipping next row so as  `
`                ``// to get the next oddRow `
`            ``oddRow = oddRow + 2;  `
`        ``}  `
`    ``} `
` `
`// Driver function `
`int` `main() { `
` `
`    ``int` `r = 3, c = 5; `
``` ```

## `Java`

``` filter_none edit close play_arrow link brightness_4 code // Java program to print matrix in zig-zag form public class GFG {     // Method to print matrix in zig-zag form     static void printZigZag(int row, int col, int a[][])     {         int evenRow = 0; // starts from the first row         int oddRow = 1; // starts from the next row            while (evenRow < row)          {             for (int i = 0; i < col; i++)             {                 // evenRow will be printed in the same direction                 System.out.print(a[evenRow][i] + " ");              }                            // Skipping next row so as to get the next evenRow             evenRow = evenRow + 2;                             if(oddRow < row)             {             for (int i = col - 1; i >= 0; i--)             {                 // oddRow will be printed in the opposite direction                 System.out.print(a[oddRow][i] + " ");              }             }                        // Skipping next row so as to get the next oddRow             oddRow = oddRow + 2;          }      }        public static void main(String[] args)     {            int r = 3, c = 5;            int mat[][] = { {1, 2, 3, 4, 5},                          {6, 7, 8, 9, 10},                          {11, 12, 13, 14, 15}};            printZigZag(r , c , mat);     } } chevron_right filter_none Python 3 filter_none edit close play_arrow link brightness_4 code # Python 3 program to print # matrix in zig-zag form    # Method to print matrix  # in zig-zag form def printZigZag(row, col, a):     evenRow = 0 # starts from the first row     oddRow = 1 # starts from the next row        while evenRow < row:          for i in range(col):                            # evenRow will be printed             # in the same direction             print(str(a[evenRow][i] ),                             end = " ")                                       # Skipping next row so as         # to get the next evenRow         evenRow = evenRow + 2                        if oddRow < row:             for i in range(col - 1, -1, -1):                                    # oddRow will be printed in                 # the opposite direction                 print(str(a[oddRow][i]),                               end = " ")                            # Skipping next row so as          # to get the next oddRow         oddRow = oddRow + 2    # Driver Code  r = 3 c = 5    mat = [[1, 2, 3, 4, 5],        [6, 7, 8, 9, 10],        [11, 12, 13, 14, 15]];    printZigZag(r , c , mat)    # This code is contributed  # by ChitraNayal chevron_right filter_none C# filter_none edit close play_arrow link brightness_4 code // C# program to print matrix in zig-zag form using System;    public class GFG {            // Method to print matrix in zig-zag form     static void printZigZag(int row, int col, int[, ] a)     {                    // starts from the first row         int evenRow = 0;                     // starts from the next row         int oddRow = 1;             while (evenRow < row) {             for (int i = 0; i < col; i++) {                                    // evenRow will be printed in                  // the same direction                 Console.Write(a[evenRow, i] + " ");             }                // Skipping next row so as to get the              // next evenRow             evenRow = evenRow + 2;                if(oddRow < row)             {                 for (int i = col - 1; i >= 0; i--)                  {                                        // oddRow will be printed in the                      // opposite direction                     Console.Write(a[oddRow, i] + " ");                 }             }                // Skipping next row so as to get              // the next oddRow             oddRow = oddRow + 2;         }     }        public static void Main()     {            int r = 3, c = 5;                    int[, ] mat = { { 1, 2, 3, 4, 5 },                         { 6, 7, 8, 9, 10 },                         { 11, 12, 13, 14, 15 }                       };            printZigZag(r, c, mat);     } }    // This code is contributed by vt_m. chevron_right filter_none PHP filter_none edit close play_arrow link brightness_4 code <?php // PHP program to print // matrix in zig-zag form    // Method to print matrix // in zig-zag form function printZigZag(\$row, \$col, \$a)     {         //starts from the first row         \$evenRow = 0;                     //starts from the next row         \$oddRow = 1;             while (\$evenRow < \$row)          {             for ( \$i = 0; \$i < \$col; \$i++)             {                 // evenRow will be printed                 // in the same direction                 echo \$a[\$evenRow][\$i], " ";              }                            // Skipping next row so as             // to get the next evenRow             \$evenRow = \$evenRow + 2;                             if(\$oddRow < \$row)             {                 for (\$i = \$col - 1; \$i >= 0; \$i--)                 {                 // oddRow will be printed in                 // the opposite direction                 echo \$a[\$oddRow][\$i], " ";                  }             }                        // Skipping next row so as              // to get the next oddRow             \$oddRow = \$oddRow + 2;          }      }    // Driver Code \$r = 3; \$c = 5; \$mat = array(array(1, 2, 3, 4, 5),              array(6, 7, 8, 9, 10),              array(11, 12, 13, 14, 15));    printZigZag(\$r , \$c , \$mat);        // This code is contributed by m_kit. ?> chevron_right filter_none ```
``` Output : 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 Time Complexity: Time complexity of the above solution is O(row*column). Related Articles: Diagonal traversal of Matrix Print matrix in antispiral form Print matrix in spiral form This article is contributed by Kamal Rawal. 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. GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details My Personal Notes arrow_drop_up Recommended Posts:Print matrix in antispiral formProgram to Print Matrix in Z formPrint a given matrix in spiral formPrint a matrix in Reverse Wave FormPrint a given matrix in reverse spiral formPrint K'th element in spiral form of matrixPrint a matrix in a spiral form starting from a pointPrint a given matrix in spiral form using direction tracking methodPrint a given matrix in counter-clock wise spiral formLargest sum Zigzag sequence in a matrixZigzag (or diagonal) traversal of MatrixProgram to print the Zigzag patternForm coils in a matrixForm a Spiral Matrix from the given ArrayProgram to print numbers in digital formImproved By : jit_t, chitranayal, RohanPrajapatijQuery('#showMoreImprove').click(function(){ jQuery(this).hide(); jQuery('#improvedByMore').css('display', 'inline'); }); Article Tags : Matrixpattern-printing Practice Tags : pattern-printingMatrix thumb_up 4 To-do Done 1.6 Based on 16 vote(s) Please write to us at contribute@geeksforgeeks.org to report any issue with the above content. Post navigation Previous first_page Maximum path sum in matrix Next last_page Matrix manipulation in Python #share-buttons img { width: 35px; padding: 5px; border: 0; box-shadow: 0; display: inline; } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most popular in Matrix Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpaintedMinimum number of operations required to set all elements of a binary matrixCheck if all the elements can be made of same parity by inverting adjacent elementsCount of numbers in given range L to R which are present in a MatrixMinimum moves taken to move coin of each cell to any one cell of Matrix More related articles in Matrix Find N in the given matrix that follows a patternPrint all possible paths from the first row to the last row in a 2D arrayReturn an array of anti-diagonals of given N*N square matrixTraverse the matrix in Diagonally Bottum-Up fashion using RecursionPath with maximum product in 2-d array ✍Write a Testimonial 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 feedback@geeksforgeeks.org COMPANY About Us Careers Privacy Policy Contact Us LEARN Algorithms Data Structures Languages CS Subjects Video Tutorials PRACTICE Courses Company-wise Topic-wise How to begin? CONTRIBUTE Write an Article Write Interview Experience Internships Videos @geeksforgeeks, Some rights reserved jQuery(document).ready(function(\$) { RESPONSIVEUI.responsiveTabs(); }) .eventLink{ border: 1px solid #868686; background-color: #e0e0e0; padding: 10px; box-shadow: none; display: block; text-align: center; color: #555 !important; font-size: 14px; font-weight: bold; } /** Side Tab Sticky Button **/ #gfg-side-sticky-tab { display: none; position: fixed; top: 60vh; left: 50px; z-index: 9999; } #gfg-side-sticky-tab div { margin: 0px; padding: 0px; } #gfg-side-sticky-tab .sticky-container { -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(-90deg); -o-transform: rotate(-90deg); border-radius: 0px 0px 6px 6px; left: -190px; position: fixed; transition-property: left; transition-duration: .6s; width: 180px; } #gfg-side-sticky-tab .sticky-container:hover { left: -10px; } #gfg-side-sticky-tab .gfg-callout { position: relative; display: block; border-radius: 0px 0px 6px 6px; } #gfg-side-sticky-tab .slideout { position: relative; vertical-align: middle; height: 180px; display: block; background-color: #fff; -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); -o-transform: rotate(90deg); overflow-y: scroll; direction: rtl; outline: 1px solid #ccc; } #gfg-side-sticky-tab .slideout .inner { text-align: center; } #gfg-side-sticky-tab .slideout .inner .inner-item { padding: 10px 0px 12px 10px; font-size: 14px; } #gfg-side-sticky-tab .slideout .inner .inner-item a { color: #404040; text-decoration: none; } #gfg-side-sticky-tab .slideout .inner .inner-item .hand-write-icon { font-size: 4rem; } #gfg-side-sticky-tab .slideout .inner .inner-item a:hover { color: #000; } #gfg-side-sticky-tab .gfg-callout .slide-out-btn { color: white; background-color: #0f9d58; height: 40px; width: 41px; margin: 0; padding: 0; display: block; text-align: center; font-size: 20px; font-weight: 600; border-radius: 0px 0px 6px 6px; position: absolute; right: -1px; border: 0; cursor: pointer; } // below changes to be added in gfg.js in future. // load comment button click when page scroll to it and positioned ad in mobile view. flag=0;jQuery(window).scroll(function(){if(jQuery('#comment').length !=0 ){var hT=jQuery('#comment').offset().top,hH=jQuery('#comment').outerHeight(),wH=jQuery(window).height(),wS=jQuery(this).scrollTop();if(wS>(hT+hH-wH-70)&&!flag){jQuery('#comment').click();flag=1}}}); /*var temp_width=jQuery(window).width();if(temp_width<468){if(jQuery('article').length>1){jQuery(jQuery('.responsiveAd')).insertAfter('article:eq(2)');jQuery('.rectangleAd').hide()} else if(jQuery('#practiceLinkDiv').length>0){jQuery(jQuery('.responsiveAd')).insertAfter('#practiceLinkDiv');jQuery('.rectangleAd').css('width','')}else{jQuery('.responsiveAd').hide();jQuery('.rectangleAd').css('width','')}} */ jQuery(document).keydown(function(e) { if (e.keyCode === 27) { jQuery(".login-modal-div").length ? jQuery(".login-modal-div").fadeOut(500) : ''; jQuery(".promotional-modal").length ? jQuery(".promotional-modal").fadeOut(500) : ''; } }); var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-12148232-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); (function(){ if(typeof _bsa !== 'undefined' && _bsa) { _bsa.init('fancybar', 'C6ADVKE', 'placement:geeksforgeeks'); } })(); ```