Question: In C++, Exercise 1 Sum of K Problem Description We are given an input file that contains word SumOfK, target number K, and a sequence
In C++, Exercise 1 Sum of K Problem Description We are given an input file that contains word SumOfK, target number K, and a sequence of N numbers. We want to determine if there are two numbers whose sum equals the given target number K. For instance, if the input file contains SumOfK // word 10 // target number K 8 4 1 6 // sequence of N numbers We know from the file that K is 10, sequence of numbers is 8 4 1 6, and number of elements N is 4 (we can count numbers). In this case, the answer is yes, there are two such numbers (4 and 6), because 4+6 is 10. One number may be used twice (doubled). If the input file is SumOfK 10 8 4 5 3 the answer is also yes, because 5+5 is 10. Exercise1 Program Devise an O(N2) algorithm to solve this problem. Code the solution. The program has to read 5 input files and print the results to corresponding 5 output files. All files have to be processed in one program run. The input files have to be named inX.txt and the output files have to be named outX.txt (where X is 1, 2, 3,4,5). The input and output files shall be in format similar to the examples below. The instructor will use different numbers to test your program.
#include #include #include #include using namespace std;
int main() { for (int i = 1; i <= 5; i++) {
// Open input and output files
ifstream in_file(string("in") + to_string(i) + string(".txt"));
ofstream out_file(string("out") + to_string(i) + string(".txt"));
// Read target number string word; int k; in_file >> word >> k;
// Read input numbers vector numbers;
int x; while (in_file >> x) {
numbers.push_back(x); }
// Check for two numbers whose sum equals the target
bool found = false; for (int j = 0; j < numbers.size(); j++) { for (int k = 0; k < numbers.size(); k++) { if (j != k && (numbers[j] + numbers[k] == k)) { found = true; break; } } if (found) break; }
// Write output file if (found) { out_file << "Yes, there are two numbers whose sum is " << k << endl; } else { out_file << "No, there are no two numbers whose sum is " << k << endl; } } return 0; }
in1.txt
SumOfK
14 5 12 8 11 7 4 3 5 5 3 2 1 14
Expected out1_sample.txt file
SumOfK
5 12 8 11 7 4 3 5 5 3 2 1
Exercise1 calculation complexity O(n^2) Yes
12+2=14
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
