In: Computer Science
Write a C++ program to find the number of pairs of integers in a given array of integers whose sum is equal to a specified number.
CODE :
#include <iostream>
using namespace std;
int main()
{
int a[1000], n;
cout << "Please enter the no of elements in an array :
\n";
cin >> n; // read n no elements in an array
cout << "please enter the array of elements : \n";
for (int i=0; i < n; i++)
{
cin >> a[i]; // read elements into an arrray
}
int sum = 0;
cout << "please enter the sum : \n";
cin >> sum; // read the sum to print the pairs
int i, count = 0;
cout <<"Array pairs whose sum equal to " <<sum
<<" is: \n";
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] + a[j] == sum)
{
cout << "\n" << a[i] << "," << a[j]; //
printing pairs that are equal to the sum
count++;
}
}
}
cout <<"\nThe no of Array pairs whose sum equal to "
<<sum <<" is: \n";
cout << count; // printing no of pairs that are equal to the
sum
return 0;
}
OUTPUT :