Print the array value which can produce the input by using addition operator

  arithmetic-expressions, arrays, c++, checksum, math

How do I edit the given program to get all possible combinations of array values which will provide the given data using addition operator?

The following code works fine only if there is only one combination. For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4. Thus the output desired is array [1] & array[3]. Attached coding works fine for this. But for array ={1, 3, 3, 4, 2}, there is two possibilities but the code returns nothing…

#include<iostream>

using namespace std;

int main() {
    int n = 5; int m = 0;
    int givendata;
    int a[n];

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    cin >> givendata;

    if (m < n) {
        for (int i = 0; i < n; i++) {
            int sum = a[n - i] + a[m];
            if (sum == givendata) {
                cout << m << " " << n - i;
            }
        }
    }

    m = m + 1;
    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT