A Sum Array Puzzle in C++?

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 22:30:26