The correct answer for the following question is d, can you explain it? What is
ID: 3606716 • Letter: T
Question
The correct answer for the following question is d, can you explain it?
What is the output of the final cout statement in the following code segment assuming that the file exam2.txt has
been opened correctly and contains the following data: 5 4 6 -1 7 8?
ifstream testin;
testin.open(“exam2.txt”);
int sum = 0, alpha;
testin>>alpha; // test to see if file opened correctly
cout<< alpha;
while (!testin.eof() && alpha != -1)
{
testin>>alpha;
sum += alpha;
testin>>alpha;
}
cout<<sum<<endl;
a. 30 d. 11
b. 3 e. 29
c. 8
Explanation / Answer
Answer: d. 11
testin>>alpha; // test to see if file opened correctly this statement will take the first value in file that is 5 but ths is not added to sum variable.
while (!testin.eof() && alpha != -1)
{
testin>>alpha;
sum += alpha;
testin>>alpha;
}
Inside while loop, we are adding alternate numbers to sum variable in the file starting from 2nd position number that is 4.
So 4 + (-1) + 8 = 11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.