The user should first input the number of testcases N, and each testcase should
ID: 3548828 • Letter: T
Question
The user should first input the number of testcases N, and each testcase should contain one integer per line. Each testcase consists of a number of lines, each line containing a single integer, terminated by a line containing the integer 0. For each testcase, we would like to know whether the testcase contains a data element x with the property that 2x is equal to the sum of the other data elements (not including x). If the testcase includes more than one element with this property then the data element, which occurs first is the one that should be printed. If no such element exists, then the number 0 should be printed.
Input
Each testcase consists of a number of lines, each line consisting of a single integer (in the range
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int array[1000];
int index=0;
int no_of_test_cases = 0;
ifstream infile("input.txt");
if(!infile)
{
cout <<"unable to open file. so Exiting from program " << endl;
return 0;
}
infile >> no_of_test_cases;
for(int i=0; i<no_of_test_cases; i++)
{
bool is_test_case_found = false;
index = 0;
infile >> array[index];
while(array[index]!=0)
{
index++;
infile >> array[index];
}
int sum=0;
for(int k=0; k<index; k++)
sum = sum + array[k];
int index_found = 0;
for(int k=0; k<index; k++)
{
if(2*array[k] == (sum-array[k]))
{
is_test_case_found = true;
index_found = k;
break;
}
}
if(is_test_case_found)
cout<< array[index_found] << endl;
else
cout<< 0 << endl;
}//end for loop
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.