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.
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>usingnamespacestd;voidtwoDimensional(vector<vector<int>>&mat){// Traverse the matrix row by row.for(inti=0;i<mat.size();i++){// Traverse the current row from left to right.for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}// Move to the next line after printing a row.cout<<"\n";}}intmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};twoDimensional(mat);return0;}
Java
importjava.util.*;classGFG{staticvoidtwoDimensional(ArrayList<ArrayList<Integer>>mat){// Traverse the matrix row by row.for(inti=0;i<mat.size();i++){// Traverse the current row from left to right.for(intj=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();}}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>mat=newArrayList<>();mat.add(newArrayList<>(Arrays.asList(1,2,3)));mat.add(newArrayList<>(Arrays.asList(4,5,6)));mat.add(newArrayList<>(Arrays.asList(7,8,9)));twoDimensional(mat);}}
Python
deftwoDimensional(mat):# Traverse the matrix row by row.foriinrange(len(mat)):# Traverse the current row from left to right.forjinrange(len(mat[i])):print(mat[i][j],end=" ")# Move to the next line after printing a row.print()# Driver Codeif__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]twoDimensional(mat)
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticvoidtwoDimensional(List<List<int>>mat){// Traverse the matrix row by row.for(inti=0;i<mat.Count;i++){// Traverse the current row from left to right.for(intj=0;j<mat[i].Count;j++){Console.Write(mat[i][j]+" ");}// Move to the next line after printing a row.Console.WriteLine();}}staticvoidMain(){List<List<int>>mat=newList<List<int>>{newList<int>{1,2,3},newList<int>{4,5,6},newList<int>{7,8,9}};twoDimensional(mat);}}
JavaScript
functiontwoDimensional(mat){// Traverse the matrix row by row.for(leti=0;i<mat.length;i++){// Traverse the current row from left to right.for(letj=0;j<mat[i].length;j++){process.stdout.write(mat[i][j]+" ");}// Move to the next line after printing a row.console.log();}}// Driver Codeconstmat=[[1,2,3],[4,5,6],[7,8,9]];twoDimensional(mat);