Arrays with for loops
Aug 20, 2018 at 2:11pm UTC
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
using namespace std;
int main() {
const int NUM_VALS = 4;
int testGrades[NUM_VALS];
int i;
int sumExtra = -9999; // Assign sumExtra with 0 before your for loop
testGrades[0] = 101;
testGrades[1] = 83;
testGrades[2] = 107;
testGrades[3] = 90;
sumExtra=0;
for (int i=0;i<NUM_VALS;++i)
{
if (testGrades[i]>100)
{
sumExtra=sumExtra+ (testGrades[i]/100);
}
}
cout << "sumExtra: " << sumExtra << endl;
return 0;
}
I tried the above code but still don't understand where I made a mistake.
Last edited on Aug 20, 2018 at 2:12pm UTC
Aug 20, 2018 at 2:13pm UTC
(testGrades[i]/100);
This is wrong.
If you have the number 107, and you want to get from it the number 7, the calculation 107/100 is not the right calculation to make.
Aug 20, 2018 at 2:47pm UTC
This looks like program 1 for a new semester...
% operator, look that up for a hint (this is the correct way to do it)
You can also cook up messy DIY logic along the lines of
extra = ( (value - 100) > 0)*(value - 100); (not recommended).
Aug 20, 2018 at 4:20pm UTC
@Repeater
When I replaced (testGrades[i]/100);
with (testGrades[i]-100);
it worked. I don't understand the reason behind it.
Topic archived. No new replies allowed.