JavaScript Grade Average Calculator

 JavaScript Grade Average Calculator Tutorial


For the next JavaScript tutorial I will be demonstrating how to make a grade average calculator. Finding the average of exam results is useful to teachers as it can reveal the general knowledge level of the class. Similarly to the last tutorial, I will split this tutorial into two skill levels with the first begin a simple grade calculator and the second having the user enter how many students sat the exam and finding the average from all their results. Here is the code for the HTML of the first example.


Nothing unusual about this compared to the other tutorial's HTML code. Lets now look at the JavaScript code.


While the code may look slightly overwhelming to beginners it is fairly easy once you understand it. We begin by creating the variables seen above. The total variable is used to get the total number of all the grades combined so it is possible to find the average. The average variable is there to print out the result at the end. The result variable is to get the grade every-time around the loop which is then passed to the total variable. The loops variable essentially tells the code how many times the loop needs to go around which represents the number of students. Finally the count variable ensures that the loop is stopped at the right time. The count <= loops code essentially means that as soon as the loop gets to the entered amount of students/loops it stops. We enter a prompt to get the first students result and it is then passed to the total variable. The number(result) code is essentially converting the result from a string to a number so the average can be calculated. Finally the count++ code is an increment which adds 1 to the count variable every-time the loop goes around to ensure that the loop stops. Once the grades are all typed in, the average variable gets the average by dividing the total by the number of loops/students. The result can be seen below.
Now that you can preform a basic loop lets increase the difficulty. The following code will ask the user to enter how many students sat the test and will then loop until it reaches the number entered. The HTML code is the exact same as the last example. Here is the JavaScript code.



While the code is quite similar, the loops variable has changed to a prompt. The final printout of the result is also changed to display how many students sat the exam. Here is a sample result of the code.




Comments