8.0k views
3 votes
Write a program that prompts the user to enter 50 integers and stores them in an array. The program then determines and outputs which numbers in the array are sum of two other array elements. If an array element is the sum of two other array elements, then for this array element, the program should output all such pairs.

User Guedes
by
5.3k points

1 Answer

3 votes

Answer:

Here is code in C++.

#include <bits/stdc++.h>

using namespace std;

int main()

{

int n=50;

// integer array to store 50 integers

int arr[n];

cout << "Enter 50 integers: ";

//read 50 integers into array

for (int i = 0; i < n; i++)

cin >> arr[i];

cout << endl;

//sort the array

sort(arr,arr+n);

// find all the pairs which give sum equal to any element of the array

for (int i = 0; i < n; i++)

{

cout<<"pair which give sum equal to ";

cout << arr[i] <<" is :";

for (int j = 0; j < n; j++)

for (int k = j + 1; k < n; k++)

if (arr[i] == arr[j] + arr[k])

cout <<"("<<arr[j]<<" & "<< arr[k] <<")"<<",";

cout << endl;

cout << "*******************************" << endl;;

}

return 0;

}

Step-by-step explanation:

Read 50 integers into an array from user.Sort the array in ascending order.Travers the sorted array and find all pairs which give sum of equal to any element of the array.Then print all such pairs.

Output:

Enter 50 integers: 23 30 34 1 3 4 9 12 96 92 80 84 123 54 67 87 34 55 21 38 29 111 10 44 103 47 83 72 77 88 80 56 49 5 102 166 134 200 205 188 178 133 154 148 162 191 193 207 209 44

pair which give sum equal to 1 is : *******************************

pair which give sum equal to 3 is : *******************************

pair which give sum equal to 4 is :(1 & 3), ******************************

pair which give sum equal to 5 is :(1 & 4), ******************************

pair which give sum equal to 9 is :(4 & 5), *******************************

pair which give sum equal to 10 is :(1 & 9), *******************************

pair which give sum equal to 12 is :(3 & 9), *******************************

pair which give sum equal to 21 is :(9 & 12), *******************************

pair which give sum equal to 23 is : *******************************

pair which give sum equal to 29 is : *******************************

pair which give sum equal to 30 is :(1 & 29),(9 & 21), *******************************

pair which give sum equal to 34 is :(4 & 30),(5 & 29), *******************************

pair which give sum equal to 34 is :(4 & 30),(5 & 29), *******************************

pair which give sum equal to 38 is :(4 & 34),(4 & 34),(9 & 29),

.

.

.

.

User ARTLoe
by
5.6k points