15,666,947 members
See more:
I'm trying to calculate the total grade and store it in an array and calculate the average grade. The total grade calculation is working fine but the average shows NaN. I don't understand why. Also The Average calculation ignores failing grades (i.e., grades less than 50).

What I have tried:

JavaScript
```courseNum=prompt("Enter the number of courses you have taken: ");

i=1;

while (i<=courseNum){
}
i++;
}

Posted
Updated 17-Sep-22 18:31pm
v2
Mike Hankey 17-Sep-22 14:01pm
Shouldn't it be;
```console.log(totalGrade/i); //this statement
```
Cloverr 17-Sep-22 17:31pm
i tried that.. doesn't work ☹️

## Solution 1

There are a couple of reasons.
Firstly because arrays in Javascript (like most other languages) are zero based: the valid indexes are `0` to `N - 1` where `N` is the number of elements.
So if you have an array of 3 elements, the valid indexes are `0`, `1`, and `2` - all other values are invalid.

Your while loop starts with `i` as `1`, and exits when it is equal to `coursenum + 1`
So if you use `i` to index into the array it will try to fetch a value that doesn't exist, and you get NAN.

And secondly, because you don't store anything into your array at all anyway! You read a value into `courseGrade` inside the loop, but at no point do you do anything with it to store it in `grades`

Either get rid of `grades` entirely - you don't need it for this anyway unless you want to list the actual values entered later in which case they need to be stored in the array - or store the values in your loop.

Finally, I'm not sure exactly what the intent of the calculation is anyway: are you to report the average passing grade, or the average grade? Because that code does neither, even when working.
so if you have five grades: `25, 25, 25, 25, 100` the average grade is `200 / 5 = 40` but the average passing grade is `100 / 1 = 100` You are returning `100 / 5` which is ... not very sensible!

Have a think about exactly what you are expected to do and decide if you need the array at all and if you perhaps need a second counter?

Cloverr 19-Sep-22 2:55am
I am trying to find the passing grade of a student by using if statement and then calculating the average of the courses that the student passed. I know my code is messed up. How can I fix it?
OriginalGriff 19-Sep-22 3:45am
"Have a think about exactly what you are expected to do and decide if you need the array at all and if you perhaps need a second counter?"

Do you need the array? Do you need a second counter?