Wednesday, 18 October 2017

Find All Pair with given sum in the array Problem Solution Using C++.

Input: 
           range = 6
           sum = 10
          ar = [3,5,4,8,2,3]
Output:
          Pair Found At Index 3 And 4

OR
Input: 
        range = 6
        sum = 10
        ar = [3,7,5,5,2,8]
Output:
        Pair Found At Index 0 And 1
        Pair Found At Index 2 And 3

        Pair Found At Index 4 And 5

Solution:

#include<bits/stdc++.h>
using namespace std;
/*
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){
    int n,sum;
    bool flag = true;
    vector<int>ar;
    cin >> n >> sum;

    for(int a, i = 0; i < n; i++){
        cin >> a;
        ar.push_back(a);
    }
    for(int i = 0; i < n; i++){
        for(int j = i+1; j < n; j++){
            if(ar[i] + ar[j] == sum){
                flag = false;
                cout << "Pair Found At Index " << i << " And " << j << endl;
            }
        }
    }
    if(flag)cout << "Pair Not Found." << endl;
    return 0;
}

No comments:

Post a Comment