Dada una array mat[][] de N * M dimensiones, la tarea es imprimir los elementos de la array usando un bucle for único .
Ejemplos:
Entrada: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Salida: 1 2 3 4 5 6 7 8 9Entrada: mat[][] = {{7, 9}, {10, 34}, {12, 15}}
Salida: 7 9 10 34 12 15
Enfoque: para atravesar la array dada usando un solo bucle, observe que solo hay N * M elementos. Por lo tanto, la idea es usar el módulo y la división para cambiar las filas y las columnas mientras se itera un solo ciclo sobre el rango [0, N * M] . Siga los pasos a continuación para resolver el problema dado:
- Iterar un ciclo sobre el rango [0, N * M] usando la variable i .
- En cada iteración, encuentre el índice de la fila y columna actual como fila = i / M y columna = i % M respectivamente.
- En los pasos anteriores, imprima el valor de mat[fila][columna] para obtener el valor de la array en ese índice.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <iostream> 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
<script> // JavaScript program for the above approach // Function to print the element // of 2D matrix using single loop function print2DMatrix(arr,rows,columns) { // Iterate over the range // [0, rows*columns] for(let i = 0; i < rows * columns; i++) { // Find row and column index let row = parseInt(i / columns, 10); let col = i % columns; // Print the element at // current index document.write(arr[row][col] + " "); } } // Given matrix mat[][] let mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; // Dimensions of the matrix let N = mat.length; let M = mat[0].length; // Function Call print2DMatrix(mat, N, M); </script>
1 2 3 4 5 6 7 8 9
Complejidad de Tiempo: O(N * M)
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA