C++ Sum Array Puzzle

C++Server Side ProgrammingProgramming

Array is a data structure that stores multiple elements of the same data type. It can store entire set of values at once. But its length needs to be defined beforehand.

In this sum array puzzle, we are given an array A1 of a definite size say n. In order to solve this puzzle, we will create an array called S1 that stores the sum of all elements of the array except the element whose position is being used. For example, if S1[3] is being calculated then we will find the sum of all elements of A1 except the element at position 4.

Examples −

Array A1 = {1,2,3,4,6}
Output S1 = {15,14,13,12,10}

Explanation − To calculate the sum array, we will add each of the elements of the initial array to a sum variable accept the value that has the same number as sum array. Which means for the first element of the sum array we will calculate the sum of all elements except the first element of the array, and the same for the whole array. Let’s calculate the values for each element of the sum array using this logic.

Sum[0], we will calculate the sum of elements except the element at 0th index. So ,

Sum[0] = 2+3+4+6 = 15

Similarly, we will calculate the value of sum[1]...

Sum[1] = 1+3+4+6 = 14

Sum[2] = 1+2+4+6 = 13

Sum[3] = 1+2+3+6 = 12

Sum[4] = 1+2+3+4 = 10

So, all elements of the sum array are not ready and the sum array is sum = {15,14,13,12,10}

Algorithm

Step 1 : Initialise a sum array sum[n] to zero, where n = size of the original array.
Step 2 : Iterate over sum[] and do :
   Step 2.1 : For sum[i], run a for loop for j -> 0 to n
   Step 2.2 : if(i != j) {sum[i] += arr[j] }
Step 3: Print sum array using std print statement.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[] = { 3, 6, 4, 8, 9 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int leftSum[n], rightSum[n], Sum[n], i, j;
   leftSum[0] = 0;
   rightSum[n - 1] = 0;
   cout<<"The original array is : \n";
   for (i = 0; i < n; i++)
      cout << arr[i] << " ";
   for (i = 1; i < n; i++)
      leftSum[i] = arr[i - 1] + leftSum[i - 1];
   for (j = n - 2; j >= 0; j--)
      rightSum[j] = arr[j + 1] + rightSum[j + 1];
   for (i = 0; i < n; i++)
      Sum[i] = leftSum[i] + rightSum[i];
   cout<<"\nThe sum array is : \n";
   for (i = 0; i < n; i++)
      cout << Sum[i] << " ";
   return 0;
}

Output

The original array is :
3 6 4 8 9
The sum array is :
27 24 26 22 21
raja
Published on 04-Oct-2019 07:56:43
Advertisements