In: Computer Science
Using pseudocode or C++ code, write a function to compute and
return the product of two sums. The first is the sum of the
elements of the first half of an array A. The second is the sum of
the elements of the second half of A. The function receives A and N
≥ 2, the size of A, as parameters. (in c++)
Code (It has been taken into account that the user will provide Array with size that is N>=2):
#include <iostream>
using namespace std;
// Function that returns the product of sum of first half of
array and
// second half of array.
int productOfSums(int A[], int N)
{
int sumHalf1 = 0; // For sum of first half.
int sumHalf2 = 0; // For sum of second half.
// For loop to calculate sum of first half.
// i is going from index 0 to N/2 - 1 so, there are two
cases:
// If N is even then the array will be split exactly into two
halves.
// If N is odd then the first half of array will contain one less
than the second half.
for(int i=0; i<N/2; i++)
sumHalf1 = sumHalf1 + A[i];
// For loop to calculate sum of second half.
for(int i=N/2; i<N; i++)
sumHalf2 = sumHalf2 + A[i];
// Just returning the product of both the sums calculated
above.
return sumHalf1*sumHalf2;
}
// main function for testing our function.
int main()
{
int A[] = {1,2,3,4,5,6}; // Sample array for testing our
productsOfSums function.
cout<<productOfSums(A,6); // Output the return value to
console.
return 0;
}
Code Screenshots:
Code Output Screenshot for the input given in main: