A Sum Array Puzzle in C++?


Here we will see one interesting problem related to array. There is an array with n elements. We have to create another array of n elements. But the i-th position of second array will hold the sum of all elements of the first array except the i-th element. And one constraint is that we cannot use the subtraction operator in this problem.

If we can use the subtraction, operation, we can easily solve this problem, by getting the sum of all elements, then subtract i-th element of first array and store it into i-th place of the second array.

Here we are solving this by adding the elements every time, and ignore the element at position i, for i in 0..n-1. Let us see the algorithm to get the point.

Algorithm

sumArray(arr, n)

begin
   define an array called res of size n
   for all elements i in arr, do
      sum := 0
      for all elements j in arr, do
         if i and j are not same, then
            sum := sum + arr[j]
         end if
      done
      res[i] = sum
   done
   return res
end

Example

 Live Demo

#include<iostream>
using namespace std;
void printArray(int arr[], int n) {
   for(int i = 0; i<n; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
void sumArray(int arr[], int resArr[], int n) {
   for(int i = 0; i<n; i++) {
      int sum = 0;
      for(int j =0; j<n; j++ ) {
         if(i != j) {
            sum += arr[j];
         }
      }
      resArr[i] = sum;
   }
}
main() {
   int myArr[7] = {5, 4, 7, 6, 9, 2, 3};
   int resArr[7];
   cout << "Initial Array: ";
   printArray(myArr, 7);
   sumArray(myArr, resArr, 7);
   cout << "Final Array: ";
   printArray(resArr, 7);
}

Output

Initial Array: 5 4 7 6 9 2 3
Final Array: 31 32 29 30 27 34 33

Updated on: 30-Jul-2019

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements