Answer to Question #145372 in C++ for Saiki

Question #145372
Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x.
1
Expert's answer
2020-11-19T08:31:19-0500
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	const int n = 10;	//size array
	int a[n];			//array

	/*Filling the array with data and displaying it on the screen.*/
	cout << "a[0.." << n - 1 << "] = [";

	srand(time(0));

	int i;
	for (i = 0; i < n; i++) {
		a[i] = rand() % 100;	//Random number from 0 to 99
		cout << a[i];
		if (i < n - 1) {
			cout << " ";
		}
		else {
			cout << "]" << endl;
		}
	}

	cout << "Enter a number to find the matching sum of the two array elements : ";
	int x;
	cin >> x;

	int j;
	for (i = 0; i < n - 1; i++) {
		for (j = i + 1; j < n; j++) {
			if (a[i] + a[j] == x) {
				cout << "a[" << i << "] + a[" << j << "] == " << x << endl;
				return 0;
			}
		}
	}
	cout << "There are no two array elements whose sum is " << x << endl;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog