In this tutorial, we will write a C++ program to find the sum and product of all elements of an array. You may go through the following topics in C++ used in the program below.
Explanation: The program takes input for the size of an array and the elements of an array. Then the array is iterated using for loop and the sum and the product of an element are calculated. Lastly, the result is displayed.
However, the program solves two separate questions at a time:
- C++ program to calculate the sum of all elements in an array
- C++ program to calculate the product of all elements in an array
C++ Program to Calculate Product and Sum of all Elements in an Array
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include<iostream> using namespace std; int main () { int arr[10], size, i, sum = 0, product = 1; //user input cout << "Enter the size of an array: "; cin >> size; cout << "Enter " << size << " elements in an array: " << endl; for (i = 0; i < size; i++) cin >> arr[i]; //calculation for (i = 0; i < size; i++) { sum += arr[i]; product *= arr[i]; } //Display cout << "\nSum of array elements: " << sum; cout << "\nProduct of array elements: " << product; return 0; } |
Output:
Enter the size of an array: 5
Enter 5 elements in an array:
2
3
4
5
6
Sum of array elements: 20
Product of array elements: 720