Cómo encontrar el producto de todos los elementos en una matriz
Una matriz es una colección de elementos almacenados en ubicaciones de memoria contiguas. Es la estructura de datos más utilizada en programación. Debe saber cómo realizar operaciones básicas en una matriz, como inserción, eliminación, recorrido, encontrar la suma de todos los elementos, encontrar el producto de todos los elementos, etc.
En este artículo, aprenderá a encontrar el producto de todos los elementos de una matriz mediante enfoques iterativos y recursivos.
Planteamiento del problema
Se le da una matriz arr . Debe encontrar el producto de todos los elementos de la matriz y luego imprimir el producto final. Debe implementar esta solución mediante bucles y recursividad.
Ejemplo 1 : Sea arr = [1, 2, 3, 4, 5, 6, 7, 8]
El producto de cada elemento de la matriz = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320
Por tanto, la salida es 40320.
Ejemplo 2 : Sea arr = [1, 1, 1, 1, 1, 1]
El producto de cada elemento de la matriz = 1 * 1 * 1 * 1 * 1 * 1 = 1
Por tanto, la salida es 1.
Enfoque iterativo para encontrar el producto de todos los elementos de la matriz
Puede encontrar el producto de todos los elementos de la matriz utilizando iteraciones / bucles siguiendo el enfoque a continuación:
- Inicialice un resultado variable (con un valor de 1) para almacenar el producto de todos los elementos de la matriz.
- Itere a través de la matriz y multiplique cada elemento de la matriz con el resultado .
- Finalmente, devuelva el resultado .
Programa C ++ para encontrar el producto de elementos de matriz usando bucles
A continuación se muestra el programa C ++ para encontrar el producto de los elementos de la matriz:
// C++ program to find the product of the array elements
#include <iostream>
using namespace std;
int findProduct(int arr[], int size)
{
int result = 1;
for(int i=0; i<size; i++)
{
result = result * arr[i];
}
return result;
}
void printArrayElements(int arr[], int size)
{
for(int i=0; i<size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
cout << "Array 1:" << endl;
printArrayElements(arr1, size1);
cout << "Product of the array elements: " << findProduct(arr1, size1) << endl;
int arr2[] = {1, 1, 1, 1, 1, 1};
int size2 = sizeof(arr2)/sizeof(arr2[0]);
cout << "Array 2:" << endl;
printArrayElements(arr2, size2);
cout << "Product of the array elements: " << findProduct(arr2, size2) << endl;
return 0;
}
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa Python para encontrar el producto de elementos de matriz usando bucles
A continuación se muestra el programa Python para encontrar el producto de los elementos de la matriz:
# Python program to find product of the list elements
def findProduct(arr, size):
result = 1
for i in range(size):
result = result * arr[i]
return result
def printListElements(arr, size):
for i in range(size):
print(arr[i], end=" ")
print()
arr1 = [1, 2, 3, 4, 5, 6, 7, 8]
size1 = len(arr1)
print("Array 1:")
printListElements(arr1, size1)
print("Product of the array elements:", findProduct(arr1, size1))
arr2 = [1, 1, 1, 1, 1, 1]
size2 = len(arr2)
print("Array 2:")
printListElements(arr2, size2)
print("Product of the array elements:", findProduct(arr2, size2))
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa JavaScript para encontrar el producto de elementos de matriz mediante bucles
A continuación se muestra el programa JavaScript para encontrar el producto de los elementos de la matriz:
// JavaScript program to find the product of the array elements
function findProduct(arr, size) {
let result = 1;
for(let i=0; i<size; i++) {
result = result * arr[i];
}
return result;
}
function printArrayElements(arr, size) {
for(let i=0; i<size; i++) {
document.write(arr[i] + " ");
}
document.write("<br>");
}
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
var size1 = arr1.length;
document.write("Array 1:" + "<br>");
printArrayElements(arr1, size1);
document.write("Product of the array elements: " + findProduct(arr1, size1) + "<br>");
var arr2 = [1, 1, 1, 1, 1, 1];
var size2 = arr2.length;
document.write("Array 2:" + "<br>");
printArrayElements(arr2, size2);
document.write("Product of the array elements: " + findProduct(arr2, size2) + "<br>");
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa C para encontrar el producto de elementos de matriz utilizando bucles
A continuación se muestra el programa en C para encontrar el producto de los elementos de la matriz:
// C program to find the product of the array elements
#include <stdio.h>
int findProduct(int arr[], int size)
{
int result = 1;
for(int i=0; i<size; i++)
{
result = result * arr[i];
}
return result;
}
void printArrayElements(int arr[], int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", arr[i]);
}
printf("n");
}
int main()
{
int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
printf("Array 1: n");
printArrayElements(arr1, size1);
printf("Product of the array elements: %d n", findProduct(arr1, size1));
int arr2[] = {1, 1, 1, 1, 1, 1};
int size2 = sizeof(arr2)/sizeof(arr2[0]);
printf("Array 2: n");
printArrayElements(arr2, size2);
printf("Product of the array elements: %d n", findProduct(arr2, size2));
return 0;
}
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Enfoque recursivo para encontrar el producto de todos los elementos en una matriz
Puede encontrar el producto de todos los elementos de la matriz utilizando la recursividad siguiendo el pseudocódigo a continuación:
function findProduct(arr,n):
if n == 0:
return(arr[n])
else:
return (arr[n] * findProduct(arr, n - 1))
Programa C ++ para encontrar el producto de elementos de matriz mediante recursividad
A continuación se muestra el programa C ++ para encontrar el producto de los elementos de la matriz:
// C++ program to find the product of the array elements using recursion
#include <iostream>
using namespace std;
int findProduct(int arr[], int n)
{
if (n == 0)
{
return(arr[n]);
}
else
{
return (arr[n] * findProduct(arr, n - 1));
}
}
void printArrayElements(int arr[], int size)
{
for(int i=0; i<size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
cout << "Array 1:" << endl;
printArrayElements(arr1, size1);
cout << "Product of the array elements: " << findProduct(arr1, size1-1) << endl;
int arr2[] = {1, 1, 1, 1, 1, 1};
int size2 = sizeof(arr2)/sizeof(arr2[0]);
cout << "Array 2:" << endl;
printArrayElements(arr2, size2);
cout << "Product of the array elements: " << findProduct(arr2, size2-1) << endl;
return 0;
}
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa Python para encontrar el producto de elementos de matriz mediante recursividad
A continuación se muestra el programa Python para encontrar el producto de los elementos de la matriz:
# Python program to find th eproduct of the list elements using recursion
def findProduct(arr, n):
if n == 0:
return(arr[n])
else:
return (arr[n] * findProduct(arr, n - 1))
def printListElements(arr, size):
for i in range(size):
print(arr[i], end=" ")
print()
arr1 = [1, 2, 3, 4, 5, 6, 7, 8]
size1 = len(arr1)
print("Array 1:")
printListElements(arr1, size1)
print("Product of the array elements:", findProduct(arr1, size1-1))
arr2 = [1, 1, 1, 1, 1, 1]
size2 = len(arr2)
print("Array 2:")
printListElements(arr2, size2)
print("Product of the array elements:", findProduct(arr2, size2-1))
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa JavaScript para encontrar el producto de elementos de matriz mediante recursividad
A continuación se muestra el programa JavaScript para encontrar el producto de los elementos de la matriz:
// JavaScript program to find the product of the array elements using recursion
function findProduct(arr, n) {
if (n == 0) {
return(arr[n]);
} else {
return (arr[n] * findProduct(arr, n - 1));
}
}
function printArrayElements(arr, size) {
for(let i=0; i<size; i++) {
document.write(arr[i] + " ");
}
document.write("<br>");
}
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
var size1 = arr1.length;
document.write("Array 1:" + "<br>");
printArrayElements(arr1, size1);
document.write("Product of the array elements: " + findProduct(arr1, size1) + "<br>");
var arr2 = [1, 1, 1, 1, 1, 1];
var size2 = arr2.length;
document.write("Array 2:" + "<br>");
printArrayElements(arr2, size2);
document.write("Product of the array elements: " + findProduct(arr2, size2) + "<br>");
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Programa C para encontrar el producto de elementos de matriz mediante recursividad
A continuación se muestra el programa en C para encontrar el producto de los elementos de la matriz:
// C program to find the product of the array elements using recursion
#include <stdio.h>
int findProduct(int arr[], int n)
{
if (n == 0)
{
return(arr[n]);
}
else
{
return (arr[n] * findProduct(arr, n - 1));
}
}
void printArrayElements(int arr[], int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", arr[i]);
}
printf("n");
}
int main()
{
int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
printf("Array 1: n");
printArrayElements(arr1, size1);
printf("Product of the array elements: %d n", findProduct(arr1, size1-1));
int arr2[] = {1, 1, 1, 1, 1, 1};
int size2 = sizeof(arr2)/sizeof(arr2[0]);
printf("Array 2: n");
printArrayElements(arr2, size2);
printf("Product of the array elements: %d n", findProduct(arr2, size2-1));
return 0;
}
Producción:
Array 1:
1 2 3 4 5 6 7 8
Product of the array elements: 40320
Array 2:
1 1 1 1 1 1
Product of the array elements: 1
Fortalezca sus conceptos de arreglos
Las matrices son una parte integral de la programación. También son uno de los temas más importantes para las entrevistas técnicas.
Si los programas basados en matrices aún le asustan, intente resolver algunos problemas básicos de matrices como cómo encontrar la suma de todos los elementos en una matriz, cómo encontrar el elemento máximo y mínimo en una matriz, cómo invertir una matriz, etc. le ayudará a fortalecer sus conceptos de matriz.