In this article, you’ll learn how to find the product of all elements in an array using iterative and recursive approaches.
Problem Statement
You’re given an array arr. You need to find the product of all elements of the array, then print the final product. You need to implement this solution using loops and recursion.
Example 1: Let arr = [1, 2, 3, 4, 5, 6, 7, 8]
The product of each element of the array = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320
Thus, the output is 40320.
Example 2: Let arr = [1, 1, 1, 1, 1, 1]
The product of each element of the array = 1 * 1 * 1 * 1 * 1 * 1 = 1
Thus, the output is 1.
Iterative Approach to Find the Product of All Elements of the Array
You can find the product of all elements of the array using iteration/loops by following the approach below:
Initialize a variable result (with a value of 1) to store the product of all elements in the array. Iterate through the array and multiply each element of the array with the result. Finally, return the result.
C++ Program to Find the Product of Array Elements Using Loops
Below is the C++ program to find the product of array elements:
Output:
Python Program to Find the Product of Array Elements Using Loops
Below is the Python program to find the product of array elements:
Output:
JavaScript Program to Find the Product of Array Elements Using Loops
Below is the JavaScript program to find the product of array elements:
Output:
C Program to Find the Product of Array Elements Using Loops
Below is the C program to find the product of array elements:
Output:
Recursive Approach to Find the Product of All Elements in an Array
You can find the product of all elements of the array using recursion by following the pseudocode below:
C++ Program to Find the Product of Array Elements Using Recursion
Below is the C++ program to find the product of array elements:
Output:
Python Program to Find the Product of Array Elements Using Recursion
Below is the Python program to find the product of array elements:
Output:
JavaScript Program to Find the Product of Array Elements Using Recursion
Below is the JavaScript program to find the product of array elements:
Output:
C Program to Find the Product of Array Elements Using Recursion
Below is the C program to find the product of array elements:
Output:
Strengthen Your Array Concepts
Arrays are an integral part of programming. They’re one of the most important topics for technical interviews as well.
If programs based on arrays still scare you, try solving some basic array problems like how to find the sum of all elements in an array, how to find the maximum and minimum element in an array, how to reverse an array, etc. It’ll help you to strengthen your array concepts.