69.7k views
5 votes
Redo Programming Exercise 14 by first sorting the array before determining the array elements that are the sum of two other elements. Use a selection sort algorithm, discussed in this chapter to sort the array.

Instructions and code for Programming Exercise 14 have been included for your convenience.
Exercise 14
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.
/*
10 17 23 65 34 6 18 27 35 110 75 25 100 24 19 67 45 88 70 96 41 36 72 150 125 25 77
200 90 166 139 55 31 8 29 119 126 137 34 62 135 121 108 197 45 35 24 1 16 43
*/
#include
using namespace std;
const int LIST_SIZE = 50;
int main()
{
int list[50];
cout << "Enter " << LIST_SIZE << " integers: ";
for (int i = 0; i < LIST_SIZE; i++)
cin >> list[i];
cout << endl;
for (int i = 0; i < LIST_SIZE; i++)
{
cout << "list[" << i << "] = " << list[i] << " is the sum of: ";
for (int j = 0; j < LIST_SIZE; j++)
for (int k = j + 1; k < LIST_SIZE; k++)
if (list[i] == list[j] + list[k])
cout << "list[" << j << "], list[" << k << "]; ";
cout << endl;
cout << "----------------------" << endl;;
}
return 0;
}

User App Pack
by
6.8k points

1 Answer

3 votes
#include
using namespace std;

const int LIST_SIZE = 50;

int main()
{
int list[50];
cout << "Enter " << LIST_SIZE << " integers: ";
for (int i = 0; i < LIST_SIZE; i++)
cin >> list[i];

// Selection sort
for (int i = 0; i < LIST_SIZE - 1; i++) {
int min_index = i;
for (int j = i + 1; j < LIST_SIZE; j++) {
if (list[j] < list[min_index]) {
min_index = j;
}
}
if (min_index != i) {
int temp = list[i];
list[i] = list[min_index];
list[min_index] = temp;
}
}

cout << endl;
for (int i = 0; i < LIST_SIZE; i++)
{
cout << "list[" << i << "] = " << list[i] << " is the sum of: ";
for (int j = 0; j < LIST_SIZE; j++)
for (int k = j + 1; k < LIST_SIZE; k++)
if (list[i] == list[j] + list[k])
cout << "list[" << j << "], list[" << k << "]; ";
cout << endl;
cout << "----------------------" << endl;;
}
return 0;
}
User Laban
by
6.9k points