Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

const int SENTINEL = -1; int count = 0; int sum = 0; int num; double average; co

ID: 3703276 • Letter: C

Question

const int SENTINEL = -1;
int count = 0;
int sum = 0;
int num;
double average;


cout << "Enter a value: (or -1 to quit): " << endl;
cin >> num;   
while (num != SENTINEL)
{
  cout << "Enter a value: (or -1 to quit): " << endl;
  cin >> num;
  count++;
  sum += num;
  }

average = sum/count;

The code above is part of a working program and has a logic error. Describe it, and indicate how to fix it.

(Remember that only partial code is shown here. The answer is not that this is an incomplete program and that a main function is needed.)

Explanation / Answer


The code has the following logic errors
1. It does not count the first value that is entered, but prompts again
2. The average is computed irrespective of if the count is 0 or +ve. The average should be computed only if there is one or more numbers entered, excluding sentinel value
Also initialize average to zero


Given below is the fixed code. Fixes shown in bold along with comment


const int SENTINEL = -1;
int count = 0;
int sum = 0;
int num;
double average = 0; //initialize average = 0

cout << "Enter a value: (or -1 to quit): " << endl;
cin >> num;
while (num != SENTINEL)
{
//first increment count, add to sum and then re-prompt for next value, changed the order of lines
count++;
sum += num;
cout << "Enter a value: (or -1 to quit): " << endl;
cin >> num;  

  
}
//calculate average only if non-zero count
if(count != 0)
average = sum/count;