The Wayback Machine - https://web.archive.org/web/20240907060356/https://www.geeksforgeeks.org/java-program-to-print-matrix-in-snake-pattern/
Open In App

Java Program to Print matrix in snake pattern

Last Updated : 07 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
68.08%
71.1K

Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern.

Examples : 

Input :mat[][] = { {10, 20, 30, 40},
                   {15, 25, 35, 45},
                   {27, 29, 37, 48},
                   {32, 33, 39, 50}};
              
Output : 10 20 30 40 45 35 25 15 27 29
         37 48 50 39 33 32 

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

 

Matrix printing

We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. 

Java




// Java program to print matrix in snake order
import java.util.*;
class GFG
{
    static void print(int [][] mat)
    {
        // Traverse through all rows
        for (int i = 0; i < mat.length; i++)
        {
 
            // If current row is even, print from
            // left to right
            if (i % 2 == 0)
            {
                for (int j = 0; j < mat[0].length; j++)
                    System.out.print(mat[i][j] +" ");
 
 
            // If current row is odd, print from
            // right to left
            }
            else
            {
                for (int j = mat[0].length - 1; j >= 0; j--)
                    System.out.print(mat[i][j] +" ");
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = new int[][]
        {
            { 10, 20, 30, 40 },
            { 15, 25, 35, 45 },
            { 27, 29, 37, 48 },
            { 32, 33, 39, 50 }
        };
 
        print(mat);
    }
}
/* This code is contributed by Mr. Somesh Awasthi */


Output : 

10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 

Time complexity: O(n^2) where n is no of elements in rows and columns

Auxiliary Space: O(1) because constant space has been used

Please refer complete article on Print matrix in snake pattern for more details!



Similar Reads

Javascript Program to Print matrix in snake pattern
Given n x n matrix In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples: Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 1 2 3 6 5 4 7 8 9 Reco
2 min read
Print matrix in snake pattern from the last column
Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in snake fashion starting from column n-1 as shown in the figure below . Examples: Input : mat[][] = 1 2 3 4 5 6 7 8 9 Output: 3 2 1 4 5 6 9 8 7 Input: mat[][] = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16 Algorithm: Start trav
6 min read
POTD Solutions | 8 Nov’ 23 | Print Matrix in snake Pattern
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Matrix but will also help you build up problem-solving skills. We recommend you to try this problem on ou
3 min read
Print matrix in snake pattern
Given an n x n matrix. In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples : Input: mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}};Output: 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input: mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};Output: 1 2 3 6 5 4 7 8 9 Rec
6 min read
Java Pattern Programs - Learn How to Print Pattern in Java
In many Java interviews Star, number, and character patterns are the most asked Java Pattern Programs to check your logical and coding skills. Pattern programs in Java help you to sharpen your looping concepts(for loop). Now if you are looking a place to get all the Java pattern exercises with solutions, then stop your search here. Here we have com
15+ min read
Convert camel case string to snake case in Java
Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string. Examples: Input: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_case Method 1: Naive Approach First we initialize a variable 'result' with an empty
3 min read
Convert Snake Case string to Camel Case in Java
Given a string in Snake Case, the task is to write a Java program to convert the given string from snake case to camel case and print the modified string. Examples: Input: str = "geeks_for_geeks" Output: GeeksForGeeks Input: str = "snake_case_to_camel_case" Output: SnakeCaseToCamelCase Method 1: Using TraversalThe idea is to first capitalize the fi
3 min read
Snake case of a given sentence
Given a sentence, task is to remove spaces from the sentence and rewrite in Snake case. It is a style of writing where we replace spaces with underscore and all words begin with small letters. Examples : Input : I got intern at geeksforgeeksOutput : i_got_intern_at_geeksforgeeks Input : Here comes the gardenOutput : here_comes_the_garden Recommende
4 min read
Find maximum length Snake sequence
Given a grid of numbers, find maximum length Snake sequence and print it. If multiple snake sequences exists with the maximum length, print any one of them. A snake sequence is made up of adjacent numbers in the grid such that for each number, the number on the right or the number below it is +1 or -1 its value. For example, if you are at location
11 min read
Snake and Ladder Problem
Given a snake and ladder board, find the minimum number of dice throws required to reach the destination or last cell from the source or 1st cell. Basically, the player has total control over the outcome of the dice throw and wants to find out the minimum number of throws required to reach the last cell.If the player reaches a cell which is the bas
15+ min read
Java Program to Print Diamond Shape Star Pattern
In this article, we are going to learn how to print diamond shape star patterns in Java. Illustration: Input: number = 7 Output: * *** ***** ******* ********* *********** ************* *********** ********* ******* ***** *** * Methods: When it comes to pattern printing we do opt for standard ways of printing them via loops only. We will try out dif
6 min read
Java Program to Print a Square Pattern for given integer
Write a java program to print the given Square Pattern on taking an integer as input from commandline. Examples: Input : 3 Output :1 2 3. 7 8 9 4 5 6 Input :4 Output :1 2 3 4 9 10 11 12 13 14 15 16 5 6 7 8 Java Code // Java program to print a square pattern with command // line one argument import java.util.*; import java.lang.*; public class Squar
2 min read
Java Program to Print Alphabet Inverted Heart Pattern
Alphabet Inverted Heart Pattern consists of two parts. The upper part of the pattern is a triangle. The base of the pattern has two peaks and a gap between them. Hence, the desired pattern looks like as shown in the illustration. Illustration: A BBB CCCCC DDDDDDD EEEEEEEEE FFFFFFFFFFF GGGGGGGGGGGGG HHHHHHHHHHHHHHH IIIIIIIIIIIIIIIII JJJJJJJJJJJJJJJJ
4 min read
Java Program to Print all the Strings that Match a Given Pattern from a File
Figure a way out to print all the strings that match a given pattern from a file. To get closer to the goal, concepts of files should be crystal clear so as to think out a way to print strings later on implementing the same to reach the final goal. So prior to dealing with the strings urgency is to discuss out file concepts. Once the file concepts
5 min read
Java Program to Print Pyramid Star Pattern
This article will guide you through the process of printing a Pyramid star pattern in Java. 1. Simple pyramid pattern Java Code import java.io.*; // Java code to demonstrate Pyramid star patterns public class GeeksForGeeks { // Function to demonstrate printing pattern public static void PyramidStar(int n) { int a, b; // outer loop to handle number
5 min read
Java Program to Print Right Triangle Star Pattern
In this article, we will learn about printing Right Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Right Triangle Star Pattern: Java Code import java.io.*; // Java code to demonstrate right star triangle public class GeeksForGeeks { // Function to demonstrate printing pattern public static void StarRightTriangl
5 min read
Java Program to Print Left Triangle Star Pattern
In this article, we will learn about printing Left Triangle Star Pattern. Examples: Input : n = 5 Output: * * * * * * * * * * * * * * * Left Triangle Star Pattern: Java Code import java.io.*; // java program for left triangle public class GFG { // Function to demonstrate printing pattern public static void StarleftTriangle(int k) { int a, b; // 1st
5 min read
Java Program to Print Spiral Pattern of Numbers
Given a number n as the size of the matrix, the task is to print a spiral pattern of size n. Examples: Input : n = 4 Output: 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Preview of the Spiral Pattern: Java Code public class GFG { public static void printSpiral(int size) { // Create row and col // to traverse rows and columns int row = 0, col = 0; int bou
3 min read
Java Program to Print Downward Triangle Star Pattern
Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like * * * * * * * * * * Example Java Code // Java Program to Print Lower Star Triangle Pattern // Main class public class GFG { // Main driver meth
2 min read
Java Program to Print Square Star Pattern
Here, we will implement a Java program to print the square star pattern. We will print the square star pattern with diagonals and without diagonals. Example: ********************** * * * * * * * * * * * * ********************** Approach: Step 1: Input number of rows and columns. Step 2: For rows of rectangle run the outer loop from 1 to rows. for (
4 min read
Java Program to Print Upper Star Triangle Pattern
The upper star triangle pattern means the base has to be at the bottom and there will only be one star to be printed in the first row. Here is the issue that will arise is what way we traverse be it forward or backward we can't ignore the white spaces, so we are not able to print a star in the first row using only two nested for loops. The answer t
2 min read
Java Program to Print Pyramid Number Pattern
Here we are getting a step ahead in printing patterns as in generic we usually play with columnar printing in the specific row keep around where elements in a row are either added up throughout or getting reduced but as we move forward we do start playing with rows which hold for outer loop in our program. Illustrations: A pyramid number pattern of
2 min read
Java Program to Print Reverse Pyramid Star Pattern
Approach: 1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object. 2. Now run two loops Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,Run an inner loop from 1 to 'i-1'Ru another inner loop from 1 to rows * 2 – (i × 2 – 1) Illustration: I
4 min read
Java Program to Print Mirror Lower Star Triangle Pattern
In this article, we are going to learn how to print mirror lower star triangle patterns in Java. Illustration: Input: number = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Methods: We can print mirror lower star triangle pattern using loops, so Using for loopUsing while lo
5 min read
Java Program to Print Mirror Upper Star Triangle Pattern
The pattern has two parts - both mirror reflections of each other. The base of the triangle has to be at the bottom of the imaginary mirror and the tip at the top. Illustration: Input: size = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Approach: Divide pattern into sub-pa
5 min read
Print lower triangular matrix pattern from given array
Given an array, print the array in 2D form where upper triangle has values 0 and lower triangle has values increasing prefix sizes (First row has prefix of size 1, second row has prefix of size 2, ..)Examples : Input : 1 2 3 4 5 Output : 1 0 0 0 0 1 2 0 0 0 1 2 3 0 0 1 2 3 4 0 1 2 3 4 5 Input : 1 2 3 Output : 1 0 0 1 2 0 1 2 3 C/C++ Code // C++ imp
6 min read
Print concentric rectangular pattern in a 2d matrix
Given a positive integer n, print the matrix filled with rectangle pattern as shown below: a a a a a a b b b a a b c b a a b b b a a a a a a where a = n, b = n - 1,c = n - 2 and so on. Examples: Input : n = 4 Output : 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Input : n = 3 Output : 3 3 3 3 3 3
13 min read
Print numbers in matrix diagonal pattern
Given an integer N, the task is to print the given pattern. Examples: Input: 3 Output: 1 2 4 3 5 7 6 8 9 Input: 4 Output: 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 Approach: Create a matrix of size N X N which will store the pattern before printing.Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and co
7 min read
Print matrix in diagonal pattern
Given a matrix of n*n size, the task is to print its elements in a diagonal pattern. Input : mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output : 1 2 4 7 5 3 6 8 9. Explanation: Start from 1 Then from upward to downward diagonally i.e. 2 and 4 Then from downward to upward diagonally i.e 7, 5, 3 Then from up to down diagonally i.e 6, 8 Then down t
15 min read
Pattern pattern() method in Java with Examples
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not accepts anything as parameter. Return Value: This
2 min read
Article Tags :
Practice Tags :