Alexis Marcelo
Alexis Marcelo

Reputation: 7

How to Iterate through arrays in C?

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

Answers (3)

HTownGirl17
HTownGirl17

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

user4527055
user4527055

Reputation:

Initialize to 0 before your for loop int sumExtra = 0;

sumExtra = testGrades[i]-100;

sumExtra += testGrades[i]-100;

Upvotes: 0

shauryachats
shauryachats

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

Related Questions