I would use the sentinel if I don't know how many items are in the list (i.e.
while (grade != -100)
. However, it is possible to perform the operations requirements for your assignment.
For the first situation, I would use an if/else statement inside the while loop on line 18.
Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
while (grade != -100 && numValues < TESTS)
{
if (/*grade is negative number*/)
{
//Notify the user the input is invalid.
// Ask the user to enter a new grade or -100 to quit.
}
else
{
scores[numValues] = grade;
numValues++;
cout << "Enter a test grade or - 100 to quit : " << endl;
cin >> grade;
}
}
|
Now for your second situation, on line 40:
for (int count = 1; count < TESTS; count++)
Two things:
First, your int count = 1
means that is starting to count your second score, not your first score. Remember, the 0 is the first element, 1 the second and so on.
Second, I crossed a line of the wrong info I gave you.
You are running the loop until count is less but not equal to TESTS. This may work if you are inputting all 20 scores (see line 6), but what if the user does not have all 20 scores? We use the sentinel to stop the list (i.e. -100). The problem with that is the loop will continue until it reaches 20 scores, which in turn will display undesired results.
One way to fix it is to change the for loop from
for (int count = 1; count < TESTS; count++)
to
for (int count = 1; count < numValues; count++)
It will run the loop until the last count in which the user inputted the sentinel value.
I hope this helps.