Related Articles
Print a given matrix in zigzag form
• Difficulty Level : Easy
• Last Updated : 04 May, 2020

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[])`
`    ``{`
`        ``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`

 `// 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);``    ``}``}`

## `Python 3`

 `# 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`

## `C#`

 `// 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.`

## `PHP`

 `= 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.``?>`

```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 MatrixPrint matrix in antispiral formPrint matrix in spiral formThis 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.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.My Personal Notes arrow_drop_upNext Zigzag (or diagonal) traversal of MatrixRecommended ArticlesPage :Largest sum Zigzag sequence in a matrix16, Apr 17Zigzag (or diagonal) traversal of Matrix14, Mar 13Program to print the Zigzag pattern22, Oct 18Print a given matrix in spiral form using direction tracking method17, Jul 19Print a given matrix in spiral form20, Aug 11Print a given matrix in counter-clock wise spiral form03, Mar 18Print a given matrix in reverse spiral form10, Jun 17Program to Print Matrix in Z form28, Sep 17Print matrix elements diagonally in spiral form06, Oct 20Print K'th element in spiral form of matrix13, Aug 16Print a matrix in Reverse Wave Form31, Jan 18Print a matrix in a spiral form starting from a point21, Aug 17Print matrix in antispiral form07, Mar 17Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix15, Jan 21Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix19, Apr 21Print Matrix after multiplying Matrix elements N times05, Nov 20Form a Spiral Matrix from the given Array20, Nov 19Check if a given matrix can be converted to another given matrix by row and column exchanges30, Apr 20Form coils in a matrix14, Feb 17Program to print numbers in digital form06, Feb 18Program to convert given Matrix to a Diagonal Matrix27, Nov 18Maximum trace possible for any sub-matrix of the given matrix12, Mar 19Minimum number of steps to convert a given matrix into Upper Hessenberg matrix27, Jun 19Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix04, Jul 19Article Contributed By : GeeksforGeeksVote for difficultyCurrent difficulty : Easy Improved By :jit_tukaspRohanPrajapatiArticle Tags :pattern-printingMatrixPractice Tags :pattern-printingMatrixReport IssueWhat’s New DSA Self Paced CourseView Details Ad free experience with GeeksforGeeks PremiumView Details var adpushup = window.adpushup = window.adpushup || {que:[]}; adpushup.que.push(function() { adpushup.triggerAd("b0696073-bfcf-4110-ba0e-0cedca76e0ee"); }); Most popular in MatrixSudoku | Backtracking-7Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)Program to multiply two matricesInplace rotate square matrix by 90 degrees | Set 1Magic Square var adpushup = window.adpushup = window.adpushup || {que:[]}; adpushup.que.push(function() { adpushup.triggerAd("570ff068-566c-4eef-bd90-7362e10ef007"); }); More related articles in MatrixMin Cost Path | DP-6Rotate a matrix by 90 degree in clockwise direction without using any extra spaceSearch in a row wise and column wise sorted matrixProgram to find the Sum of each Row and each Column of a MatrixGold Mine Problem var adpushup = window.adpushup = window.adpushup || {que:[]}; adpushup.que = window.adpushup.que || []; adpushup.que.push(function() { adpushup.config.platform !== 'MOBILE' && window.adpushup.utils.dockify.dockifyAd(`#fda8892c-aa7b-43f9-bffc-daf5422c2c5e`, { bottomOffset: '110', bottomXpath: '#gfg-footer', css: { 'z-index': "0", background: 'transparent', 'margin-top': '100px'}, event: 'scriptLoaded', eventData: {value: ''}, format: 'docked', operation: 'APPEND', placement: 'default', type: 'docked', xpath: '#AP_G4GR_4' }, window.adpushup.utils); adpushup.triggerAd("fda8892c-aa7b-43f9-bffc-daf5422c2c5e"); }); Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305 feedback@geeksforgeeks.orgCompanyAbout UsCareersPrivacy PolicyContact UsCopyright PolicyLearnAlgorithmsData StructuresLanguagesCS SubjectsVideo TutorialsPracticeCoursesCompany-wiseTopic-wiseHow to begin?ContributeWrite an ArticleWrite Interview ExperienceInternshipsVideos@geeksforgeeks , Some rights reservedjQuery(document).ready(function(\$) { RESPONSIVEUI.responsiveTabs(); })We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy 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'); s.parentNode.insertBefore(ga, s); })(); try { var isAdblockEnabled = t => fetch( new Request('https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', { method: 'HEAD', mode: 'no-cors' }) ).catch(t); isAdblockEnabled(() => { var scr = window.document.createElement('script'), siteId = 41782; scr.setAttribute('src', 'https://delivery.adrecover.com/'.concat(siteId, '/adRecover.js')); scr.setAttribute('type', 'text/javascript'); scr.setAttribute('async', !0); window.document.head.append(scr); }); } catch (err) {console.log(err);} (function(){ if(typeof _bsa !== 'undefined' && _bsa) { _bsa.init('fancybar', 'C6ADVKE', 'placement:geeksforgeeks'); } })(); ```