
Ralph W. answered 06/08/21
From Syntax to Systems: Professional Tutoring in Computer Programming
// VectorTargetDemo.cpp : This file contains the 'main' function. Program execution begins and ends there.
// Input: nums = [2,7,11,15], target = 9
//Output: [0, 1]
//Output : Because nums[0] + nums[1] == 9, we return[0, 1].
#include
#include
#include
using namespace std;
int main()
{
cout << "Hello World!" << endl;
string input;
vector nums(5);
int numbers = 0;
int target = 0;
bool gotIt = false;
int firstIndex = 0;
int secondIndex = 0;
cout << "Enter array of integers and a integer" << endl;
cout << "Enter array of integers seperated by comma" << endl;
cin >> input;
for (int i = 0; i < input.size(); i++)
{
string temp = input.substr(i, 1);
if (temp != ",")
{
int num = stoi(temp);
nums[i / 2] = num;
numbers++;
}
}
cout << "Enter a integer" << endl;
cin >> input;
for (int i = 0; i < input.size(); i++)
{
string temp = input.substr(i, i + 1);
int num = stoi(temp);
target = num;
}
for (int i = 0; i < numbers; i++)
{
for (int j = i; j < numbers; j++)
{
int sum = nums[i] + nums[j];
if (sum == target)
{
gotIt = true;
firstIndex = i;
secondIndex = j;
break;
}
}
if (gotIt)
{
cout << "Result: [" << firstIndex << ", " << secondIndex;
cout << "] , " << target << endl;
break;
}
}
cout << "Output: [";
for (int x : nums)
cout << x << " ";
cout << "] , " << target << endl;
}