Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program for product of array
Given an array arr[n] of n number of elements, the task is to find the product of all the elements of that array.
Like we have an array arr[7] of 7 elements so its product will be like −
Syntax
int productOfArray(int arr[], int n);
Example: Input and Output
Input: arr[] = { 10, 20, 3, 4, 8 }
Output: 19200
Explanation: 10 × 20 × 3 × 4 × 8 = 19200
Input: arr[] = { 1, 2, 3, 4, 3, 2, 1 }
Output: 144
Algorithm
- Initialize a variable
resultto 1 - Iterate through each element of the array
- Multiply each element with the
result - Return the final
result
Example: Product of Array Elements
#include <stdio.h>
int prod_arr(int arr[], int n) {
int result = 1;
// Multiply each element and store it in result
for (int i = 0; i < n; i++) {
result = result * arr[i];
}
return result;
}
int main() {
int arr[] = { 10, 20, 3, 4, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Product of array elements: %d<br>", prod_arr(arr, n));
return 0;
}
Product of array elements: 19200
Key Points
- Initialize the result variable to 1, not 0, since multiplying by 0 gives 0
- The time complexity is O(n) where n is the number of elements
- Space complexity is O(1) as only one extra variable is used
Conclusion
Finding the product of array elements is straightforward using a simple loop. Initialize the result to 1 and multiply each element sequentially to get the final product.
Advertisements
