Print a 2D Array or Matrix using single loop (original) (raw)
Last Updated : 08 Jun, 2021
Given a matrix mat[][] of N * M dimensions, the task is to print the elements of the matrix using a single for loop.
Examples:
Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Output: 1 2 3 4 5 6 7 8 9Input: mat[][] = {{7, 9}, {10, 34}, {12, 15}}
Output: 7 9 10 34 12 15
Approach: To traverse the given matrix using a single loop, observe that there are only N * M elements. Therefore, the idea is to use modulus and division to switch the rows and columns while iterating a single loop over the range [0, N * M]. Follow the steps below to solve the given problem:
- Iterate a loop over the range [0, N * M] using the variable i.
- At each iteration, find the index of the current row and column as row = i / M and column = i % M respectively.
- In the above steps, print the value of mat[row][column] to get the value of the matrix at that index.
Below is the implementation of the above approach:
C++ `
// C++ program for the above approach #include using namespace std;
// Function to print the element // of 2D matrix using single loop void print2DMatrix(int arr[][3], int rows, int columns) {
// Iterate over the range
// [0, rows*columns]
for(int i = 0; i < rows * columns; i++)
{
// Find row and column index
int row = i / columns;
int col = i % columns;
// Print the element at
// current index
cout << arr[row][col] << " ";
}
}
// Driver Code int main() {
// Given matrix mat[][]
int mat[][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
// Dimensions of the matrix
int N = sizeof(mat) / sizeof(mat[0]);
int M = sizeof(mat[0]) / sizeof(mat[0][0]);
// Function Call
print2DMatrix(mat, N, M);
return 0;
}
// This code is contributed by akhilsaini
Java
// Java Program for the above approach
import java.io.*;
class GFG {
// Function to print the element
// of 2D matrix using single loop
public static void print2DMatrix(
int arr[][], int rows, int columns)
{
// Iterate over the range
// [0, rows*columns]
for (int i = 0;
i < rows * columns; i++) {
// Find row and column index
int row = i / columns;
int col = i % columns;
// Print the element at
// current index
System.out.print(
arr[row][col] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
// Given matrix mat[][]
int[][] mat = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
// Dimensions of the matrix
int N = mat.length;
int M = mat[0].length;
// Function Call
print2DMatrix(mat, N, M);
}
}
Python3
Python3 program for the above approach
Function to print the element
of 2D matrix using single loop
def print2DMatrix(arr, rows, columns):
Iterate over the range
[0, rows*columns]
for i in range(0, rows * columns):
# Find row and column index
row = i // columns
col = i % columns
# Print the element at
# current index
print(arr[row][col], end = ' ')
Driver Code
if name == 'main':
Given matrix mat[][]
mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Dimensions of the matrix
N = len(mat) M = len(mat[0])
Function Call
print2DMatrix(mat, N, M)
This code is contributed by akhilsaini
C#
// C# program for the above approach using System;
class GFG{
// Function to print the element // of 2D matrix using single loop public static void print2DMatrix(int[, ] arr, int rows, int columns) {
// Iterate over the range
// [0, rows*columns]
for(int i = 0; i < rows * columns; i++)
{
// Find row and column index
int row = i / columns;
int col = i % columns;
// Print the element at
// current index
Console.Write(arr[row, col] + " ");
}
}
// Driver Code public static void Main() {
// Given matrix mat[][]
int[, ] mat = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
// Dimensions of the matrix
int N = mat.GetLength(0);
int M = mat.GetLength(1);
// Function Call
print2DMatrix(mat, N, M);
} }
// This code is contributed by akhilsaini
JavaScript
`
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Similar Reads
- Print n x n spiral matrix using O(1) extra space Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space. Example : Input: n = 5 Output: 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 We strongly recommend you to minimize your browser and try this yourself first. The sol 9 min read
- Program to print Lower triangular and Upper triangular matrix of an array Prerequisite - Multidimensional Arrays in C / C++Given a two dimensional array, Write a program to print lower triangular matrix and upper triangular matrix. Lower triangular matrix is a matrix which contains elements below principal diagonal including principal diagonal elements and rest of the ele 9 min read
- Emulating a 2-d array using 1-d array How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. m x n). If the elements in the 2-d array are stored in row-major order. Then, the element at 5 min read
- Row wise sorting a 2D array Given a 2D array, sort each row of this array and print the result.Examples: Input : mar[][] = [ [77, 11, 22, 3], [11, 89, 1, 12], [32, 11, 56, 7], [11, 22, 44, 33] ] Output : mat[][] = [ [3, 11, 22, 77], [1, 11, 12, 89], [7, 11, 32, 56], [11, 22, 33, 44] ] Input : mat[][] = [ [8, 6, 4, 5], [3, 5, 2 4 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 6 min read
- Print Kth boundary of a Matrix Given a square matrix mat[][] and a positive integer K. The task is to print the Kth boundary of mat[][]. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, K = 1 {6, 7, 8, 9, 10} {11, 12, 13, 14, 15} {16, 17, 18, 19, 20} {21, 22, 23, 24, 25}}Output: 1 2 3 4 5 6 10 11 15 16 20 21 22 23 24 25 Explanation: 7 min read
- Program to print the Diagonals of a Matrix Given a 2D square matrix, print the Principal and Secondary diagonals. Examples : Input: 41 2 3 44 3 2 17 8 9 66 5 4 3Output:Principal Diagonal: 1, 3, 9, 3Secondary Diagonal: 4, 2, 8, 6Input:31 1 11 1 11 1 1Output:Principal Diagonal: 1, 1, 1Secondary Diagonal: 1, 1, 1For example, consider the follow 14 min read
- Convert given upper triangular Matrix to 1D Array Given an upper triangular matrix M[][] of dimensions N * N, the task is to convert it into an one-dimensional array storing only non-zero elements from the matrix. Examples: Input: M[][] = {{1, 2, 3, 4}, {0, 5, 6, 7}, {0, 0, 8, 9}, {0, 0, 0, 10}}Output: Row-wise: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Colu 12 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 4 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 13 min read