1// C++ program to check if given array
2// has 2 elements whose sum is equal
3// to the given value
4
5#include <bits/stdc++.h>
6using namespace std;
7
8// Function to check if array has 2 elements
9// whose sum is equal to the given value
10bool hasArrayTwoCandidates(int A[], int arr_size,
11 int sum)
12{
13 int l, r;
14
15 /* Sort the elements */
16 sort(A, A + arr_size);
17
18 /* Now look for the two candidates in
19 the sorted array*/
20 l = 0;
21 r = arr_size - 1;
22 while (l < r) {
23 if (A[l] + A[r] == sum)
24 return 1;
25 else if (A[l] + A[r] < sum)
26 l++;
27 else // A[i] + A[j] > sum
28 r--;
29 }
30 return 0;
31}
32
33/* Driver program to test above function */
34int main()
35{
36 int A[] = { 1, 4, 45, 6, 10, -8 };
37 int n = 16;
38 int arr_size = sizeof(A) / sizeof(A[0]);
39
40 // Function calling
41 if (hasArrayTwoCandidates(A, arr_size, n))
42 cout << "Array has two elements with given sum";
43 else
44 cout << "Array doesn't have two elements with given sum";
45
46 return 0;
47}