...

/

Solution Review: Array of Products of All Elements

Solution Review: Array of Products of All Elements

This review provides a detailed analysis of how to solve the "Array of Products of All Elements" challenge.

We'll cover the following...

Solution #

Press + to interact
namespace chapter_2
{
class Solution
{
// Array of Products of all Elements
static int[] findProduct(int []arr, int size)
{
int n = size;
int i, temp = 1;
int[] product = new int[n]; // Allocate memory for the product array
// temp contains product of elements on left side excluding arr[i]
for (i = 0; i < n; i++)
{
product[i] = temp;
temp *= arr[i];
}
temp = 1; // Initialize temp to 1 for product on right side
// temp contains product of elements on right side excluding arr[i]
for (i = n - 1; i >= 0; i--)
{
product[i] *= temp;
temp *= arr[i];
}
return product;
}
static void Main(string[] args)
{
int size = 4;
int []arr = { 1, 3, 4, 5 };
Console.Write( "Array before product: ");
for (int i = 0; i < size; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine("");
int[] prodArray = findProduct(arr, size);
Console.Write("Array after product: ");
for (int i = 0; i < size; i++)
{
Console.Write(prodArray[i] + " ");
}
return ;
}
}
}

Explanation

In this problem, you need to calculate the product of elements in a specific way. In the output array, the value at index i will be equal to the product of all the elements of the ...