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:
- Run a loop from 0 to N*N
- For every iteration i, find the current index modulo row number.
- 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)