Reputation: 7
So I need to fill in the code for the program to work for the question:
Array testGrades contains NUM_VALS
test scores. Write a for loop that sets sumExtra
to the total extra credit received. Full credit is 100, so anything over 100 is extra credit. Ex: If testGrades = {101, 83, 107, 90}
, then sumExtra = 8
, because 1 + 0 + 7 + 0 is 8.
#include <stdio.h>
int main(void) {
const int NUM_VALS = 4;
int testGrades[NUM_VALS];
int i = 0;
int sumExtra = -9999; // Initialize to 0 before your for loop
testGrades[0] = 101;
testGrades[1] = 83;
testGrades[2] = 107;
testGrades[3] = 90;
// STUDENT CODE GOES HERE
return 0;
}
So far all I have is:
for (i=0;i<NUM_VALS;++i) {
if (testGrades[i] > 100) {
sumExtra = testGrades[i] - 100;
}
}
I dont know how to find the sum of the array of the values over 100.
Upvotes: 0
Views: 11749
Reputation: 403
You are missing the if statement that checks if the test score is above 100. Here is the code that works:
sumExtra = 0;
for (i = 0; i < NUM_VALS; ++i) {
if (testGrades[i] >= 101) {
sumExtra += (testGrades[i] - 100);
}
}
cout << "sumExtra: " << sumExtra << endl;
Upvotes: 1
Reputation:
Initialize to 0 before your for loop int sumExtra = 0;
sumExtra = testGrades[i]-100;
sumExtra += testGrades[i]-100;
Upvotes: 0
Reputation: 10385
Firstly, initialise sumExtra
to 0. Then just change:
sumExtra = testGrades[i] - 100;
to
sumExtra += testGrades[i] - 100;
because the sumExtra
for a particular index i
is testGrades[i]-100
, and you want to find the total of the sumExtra
, and hence keeping adding this to the sumExtra
variable.
Upvotes: 2