Print the elements of a matrix using a single loop

Updated

Given a matrix of size N*N, the task is to print the elements of the matrix using a single loop.

Examples :

Input : 1  2  3
        4  5  6
        7  8  9
Output : 1 2 3 4 5 6 7 8 9

Input : 1  2
        3  4
Output : 1 2 3 4

Approach :

The matrix of size N*N  can be computed as a 1-D matrix of size N*N. Follow the below steps to solve the problem:

  1. Run a loop  from 0 to N*N 
  2. For every iteration i, find the current index modulo row number.
  3. Print the current index as A[i/N][i%N]

Implementation :

// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;

#define N 3
// Function to print matrix
void printMatrix(int A[N][N])
{
    
    for(int i = 0;i < N * N;i++){
		int row = i / N;
		
		int col=i % N;
		
		cout<< A[row][col]<<" ";
	}
	
}

// Driver Code
int main()
{
	int A[3][3]={{1, 2, 3},
		         {4, 5, 6},
		         {7, 8, 9}};
	
	// Function Call
	printMatrix(A);

    return 0;
}

Output :

1 2 3 4 5 6 7 8 9

Time Complexity : O(N * N)

Space Complexity : O(1)

Comment
Next tutorial
Mithlesh Upadhyay Published 1 Dec 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials