-1

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;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 4
    "For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4" .. what about 1 and 5? – yano Oct 08 '21 at 22:02
  • First, solve your algorithm on paper. Second, code it. Don't try to code your solution directly. – Melon Oct 12 '21 at 14:23

1 Answers1

1

You need to use a double loop to compare all the values:

// start at 0, the first position of the array. Loop until the 2nd to last element
for (int i=0; i<n-1;i++)
{
  // start this index at one higher than i. Since a+b == b+a, there's no need to
  // add the later values in the array with the previous ones, we've already
  // done that
  for (int j=i+1; j<n; j++)
  {
    int sum = a[i]+a[j];
    if (sum == givendata)
    {
      std::cout << a[i] << " + " << a[j] << " = " << givendata << std::endl;
    }
  }
}

Demonstration

Also see Why is "using namespace std;" considered bad practice?

yano
  • 4,827
  • 2
  • 23
  • 35