Matrix Traversal

Last Updated : 27 Aug, 2026

Given a square matrix mat[][] of size n * n, print all its elements in row-major order, where each row is printed in a new line and the elements in a row are printed from left to right.

Examples: 

Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

154

Output:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Explanation: The elements of the matrix are printed row by row, from left to right.

Input: mat[][] = [[5]]
Output: 5
Explanation: The matrix contains only one element, which is printed.

Try It Yourself
redirect icon

Traversal Using Nested Loops - O(n ^ 2) Time and O(1) Space

The idea is to use two nested loops: the outer loop processes each row, while the inner loop prints all elements of that row. This ensures every element is visited exactly once.

  • Start from the first row of the matrix.
  • Traverse each row from left to right.
  • Print every element of the current row.
  • After completing a row, move to the next row.
  • Repeat until all rows are processed.
  • Print a newline after each row.
C++
#include <bits/stdc++.h>
using namespace std;

void twoDimensional(vector<vector<int>> &mat)
{
    // Traverse the matrix row by row.
    for (int i = 0; i < mat.size(); i++)
    {
        // Traverse the current row from left to right.
        for (int j = 0; j < mat[i].size(); j++)
        {
            cout << mat[i][j] << " ";
        }

        // Move to the next line after printing a row.
        cout << "\n";
    }
}

int main()
{
    vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    twoDimensional(mat);

    return 0;
}
Java
import java.util.*;

class GFG {
    static void twoDimensional(ArrayList<ArrayList<Integer> > mat)
    {
        // Traverse the matrix row by row.
        for (int i = 0; i < mat.size(); i++) {

            // Traverse the current row from left to right.
            for (int j = 0; j < mat.get(i).size(); j++) {
                System.out.print(mat.get(i).get(j) + " ");
            }

            // Move to the next line after printing a row.
            System.out.println();
        }
    }

    public static void main(String[] args)
    {
        ArrayList<ArrayList<Integer> > mat = new ArrayList<>();

        mat.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
        mat.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
        mat.add(new ArrayList<>(Arrays.asList(7, 8, 9)));

        twoDimensional(mat);
    }
}
Python
def twoDimensional(mat):

    # Traverse the matrix row by row.
    for i in range(len(mat)):

        # Traverse the current row from left to right.
        for j in range(len(mat[i])):
            print(mat[i][j], end=" ")

        # Move to the next line after printing a row.
        print()


# Driver Code
if __name__ == "__main__":
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    twoDimensional(mat)
C#
using System;
using System.Collections.Generic;

class GFG {
    static void twoDimensional(List<List<int>> mat)
    {
        // Traverse the matrix row by row.
        for (int i = 0; i < mat.Count; i++) {
            
            // Traverse the current row from left to right.
            for (int j = 0; j < mat[i].Count; j++) {
                Console.Write(mat[i][j] + " ");
            }

            // Move to the next line after printing a row.
            Console.WriteLine();
        }
    }

    static void Main()
    {
        List<List<int> > mat = new List<List<int> >{
            new List<int>{ 1, 2, 3 },
            new List<int>{ 4, 5, 6 },
            new List<int>{ 7, 8, 9 }
        };

        twoDimensional(mat);
    }
}
JavaScript
function twoDimensional(mat)
{
    // Traverse the matrix row by row.
    for (let i = 0; i < mat.length; i++) {

        // Traverse the current row from left to right.
        for (let j = 0; j < mat[i].length; j++) {
            process.stdout.write(mat[i][j] + " ");
        }

        // Move to the next line after printing a row.
        console.log();
    }
}

// Driver Code
const mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];

twoDimensional(mat);

Output
1 2 3 
4 5 6 
7 8 9 
Comment