How to calculate average grade - javascript

I'm new to JavaScript and can't seem to figure out why my last function is not doing what it's suppose to do which is to use the average of entered grades(number) from the user to return a letter grade.
My first function is working how it should and my second function is written correctly (I think) but for my third function i'm not sure what i'm doing wrong because when I test run nothing shows up.
Here is what I've done within my code:
var grades = [];
var totalSum = 0;
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
var average = totalSum / grades.length;
}
}
function letterGrade() {
if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();

You need average variable as global and some fix in your letterGrade() like this :
add: letterGrade() will always return A if score is 90 or below
var grades = [];
var totalSum = 0;
var average = 0
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (average >= 90 && average <= 100) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average >= 80 && average <= 89) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average >= 70 && average <= 79) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average >= 60 && average <= 69) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else if (average <= 59) {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>

It is a scope problem. You need to define the variable average at the top and not inside the function gradeAverage.
var grades = [];
var totalSum = 0;
var average = 0; /* Added */
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>

3 issues here:
In the 3rd function you use 'average' event though its not defined globally - meaning its not available in the function.
It seems you check totalSum <= x even though you probably want to check average <= x.
The order of checks in the 3rd function will always result in the first check. Because even if average <= 60 its also <= 90. Reverse the order of checks so the lower grades will be first:
if (totalSum <= 50) {
document.getElementById("finalGrade").innerHTML += average + " F";
} else if(totalSum <= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else if (totalSum <= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (totalSum <= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (totalSum <= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else {
document.getElementById("finalGrade").innerHTML += average + " A+";
}

move the average var declaration outside the function (not really recommended, see later)
reverse the ifs from <= to >=
use average and not total sum in the ifs
var grades = [];
var totalSum = 0;
var average =0;
// function to read five values from series of prompts stored in array
function myFunction() {
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
}
// function to calculate the average of the five entered grades and store it in a variable
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade() {
if (average>= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average>= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average>= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average>= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
myFunction();
gradeAverage();
letterGrade();
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>
Better, pass the var:
// function to read five values from series of prompts stored in array
function getGrades() {
var grades = [];
for (var i = 0; i < 5; i++) {
grades[i] = parseInt(prompt("Enter a Grade: "));
document.getElementById("gradeInput").innerHTML += grades[i] + " ";
}
return grades;
}
// function to calculate the average of the five entered grades and store it in a variable
function getSum(grades) {
var totalSum = 0;
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
}
return totalSum;
}
// funtion to use the average of entered grades to determine letter grade that it will return to the user
function letterGrade(grades) {
var totalSum = getSum(grades);
var average = totalSum / grades.length;
var finalGrade = "";
if (average >= 90) {
finalGrade = "A";
} else if (average >= 80) {
finalGrade = "B";
} else if (average >= 70) {
finalGrade = "C";
} else if (average >= 60) {
finalGrade = "D";
} else {
finalGrade = "F";
}
document.getElementById("finalGrade").innerHTML += average + " " + finalGrade;
}
var grades = getGrades()
letterGrade(grades);
<p id="gradeInput">You entered the following grades: </p>
<p id="finalGrade">Your grade average is: </p>

Before giving the solution you need to understand the scopes of variables in javascript.
Consider the following code:
function myFunction() {
var carName = "Volvo";
//code here CAN use the variable carName
}
function someAnotherFunction(){
console.log(carName);
//code here CANNOT use the variable carName
//It will the error that carName is not defined.
}
//code here CANNOT use the variable carName
Another case:
var carName = "Volvo";
function myFunction() {
console.log(carName);
//code here CAN use the variable carName
}
function someAnotherFunction(){
console.log(carName);
//code here CAN use the variable carName
}
console.log('Check my value here again: '+carName);
//code here CAN also use the variable carName
The difference to note here is, The scope/visibility of variable is limited to opening and closing brackets in which it is placed. Outside the closing brackets the very same variable won't be visible outside the brackets, in which it was declared.
Same way you cannot use average variable outside the brackets from where it was declared.
Looking at your code few things needs to be changed.
Move the average declaration outside the brackets, so that it becomes visible.
var average =0;
function gradeAverage() {
for (var i = 0; i < grades.length; i++) {
totalSum += grades[i];
average = totalSum / grades.length;
}
}
And in the function where grades are calculated, the condition when the average is greater than 90 needs to be added.
function letterGrade() {
if (average >= 90) {
document.getElementById("finalGrade").innerHTML += average + " A";
} else if (average >= 80) {
document.getElementById("finalGrade").innerHTML += average + " B";
} else if (average >= 70) {
document.getElementById("finalGrade").innerHTML += average + " C";
} else if (average >= 60) {
document.getElementById("finalGrade").innerHTML += average + " D";
} else {
document.getElementById("finalGrade").innerHTML += average + " F";
}
}
Rest would be fine as it is.
Hope this helps.

Related

Unlimited 6 sided dice roller

Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?
We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.
The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.
When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.
I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?
JS
function rollDice() {
var numDice = document.getElementById("diceNum").value;
var container = document.getElementById("dieContainer");
container.innerHTML = "";
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
};
var x, text;
x = document.getElementById("diceNum").value;
if (isNaN(x) || x < 1 || x > 5) {
window.alert('Input not valid');
document.getElementById("dieContainer").style.display = "none";
} else {
document.getElementById("dieContainer").style.display = "block";
}
};
EDIT
I updated it to this now
let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
console.log("You got a 6 och two new dices were thrown");
document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
} else {
sum += diceRoll;
console.log(sum);
document.getElementById("msg").innerHTML = "Result: " + sum;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?
Replace loop for by loop while:
let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
} else {
sum += diceRoll;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
You can do something like this:
function rollDice() {
var numDice = Number(document.getElementById("diceNum").value);
if (isNaN(numDice) || numDice < 1 || numDice > 5) {
window.alert('Input not valid');
return
}
var container = document.getElementById("dieContainer");
container.innerHTML = "";
var total = 0
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
if(diceRoll === 6) {
//Increase the maximum by 1 (because ignore 6: -1; add two: +2)
numDice++
//Decrease the current by 1 (to ignore the 6)
i--
continue
}
total += diceRoll
};
document.getElementById("diceTotal").innerText = total
document.getElementById("diceCount").innerText = numDice
}
<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>

Adding a line break after every 12 numbers inside a for loop in Javascript

My current code is:
for (count = 1; count <= 100; count = count + 1) {
text = "<br>" + " " + count;
document.getElementById("id").innerHTML += text;
}
When displaying it I need to add a line break after every 12 numbers in a line.
for (count = 1; count <= 100; count = count + 1) {
text = "<br>" + " " + count;
if (count % 12 === 0) {
document.getElementById("id").innerHTML += text;
}
}
You could take the reminder operator % and check if the result is zero.
Some annotations:
declare all variables,
collect all text,
assign to element at the end.
var text = "";
for (let count = 1; count <= 100; count++) {
text += count + ' ';
if (count % 12 === 0) {
text += "<br>";
}
}
document.getElementById("demo5").innerHTML += text;
<div id="demo5"></div>
You can help yourself with the % (remainder) operator. If number % 12 === 0 is because that number is a multiple of 12. You can use this to your advantage like so
var text = "";
for (let count = 1; count <= 100; count++) {
text += count + ' ';
if (count % 12 === 0) {
text += "<br>";
}
}
document.getElementById("answer").innerHTML += text;
<div id="answer"></div>
Another way could be to explicitly count how many items you're currently having and reset that count whenever it reaches 12:
var text = "";
var n = 0;
for (let count = 1; count <= 100; count++) {
text += count + ' ';
n++;
if (n === 12) {
n = 0;
text += "<br>";
}
}
document.getElementById("answer").innerHTML += text;
<div id="answer"></div>
Do the following
for (count = 1; count <= 100; count = count + 1) {
text += count+ " ";
if(count%12 == 0){
text = text + "</br>";
}
document.getElementById("id").innerHTML = text;
}

How to display average from list using javascript?

I just want to show their average from the list when the user stored a value in the list
But I try to use document.write(); but it's doesn't work for me
I want to show the average below the list
function listtable()
{
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++)
{
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(score[i]);
}
var avarage = sum/scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}
You have a couple of typos in your code:
parseInt(score[i]) should be parseInt(scoreArray[i])
i < scoreArray.Length should be scoreArray.length with a lowercase l
The variable should be average not avarage
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do {
score = prompt("Please enter score and Enter -1 to stop entering ");
score = parseInt(score);
if (score >= 0) {
scoreArray[scoreArray.length] = score;
}
}
while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.length; i++) {
sum += parseInt(scoreArray[i]);
}
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}
listtable()
<span id="display" />
(Please search how to debug javascript code using degbugger; and dev tools. You can avoid trivial errors)
Try this:
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
var i;
do {
score = prompt("Please enter score and Enter -1 to stop entering");
score = parseInt(score);
if (score >=0 ) {
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
console.log(scoreArray[i])
sum += parseInt(scoreArray[i]);
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Average Score is: " + average);
}
listtable();
<div id="display"></div>
I have made the following changes in your code:
You have used 2 for loop which is not needed, I have added the code in the single for loop. (Optimized, Not an issue)
The variable name is defined as average but you used avarage in the document.write.
You didn't define the var i in your code and directly initializing it in the loop.
There are multiple issue in your code,
You need to store elements in an array with incremental counter instead of storing it in an array length i.e Intested of scoreArray[scoreArray.length] = score; you need to store value at particular index.
Like.
var index = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[index++] = score;
//Use index with incremental operator
}
} while (score != -1);
While calculating sum you need to read value from scoreArray not from score. In your code scoreArray is an array not score variable.
correct code,
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(scoreArray[i]);
//Use scoreArray instead of score
}
Now calculate average and print in HTML DOM
Like,
document.write("The Avarage Score is: " + avg);
Here is sample piece of code to print average.
//Declaration of variables
var scoreArray = [1, 2, 3, 4, 5];
var i, index = 0, sum = 0;
//Calculate sum
for(i = 0; i < scoreArray.length; i++)
sum += scoreArray[i];
//Calculate average
var avg = sum/scoreArray.length;
document.write("The Avarage Score is: " + avg);

JavaScript- get sum of values inside a for loop

I'm trying to sum all the variables,
as many times as they appear in the loop,
that is- for example if hitpoints appears
3 times(as in my code) sum -12 + -12 + -12;
And then at the end I need a final result - a
sum of all of the variable values as many
times as they appear.
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);
I assume you want the sum of the points.
Declare a variable sum and keep incrementing
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
var sum=0;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
sum += hitpoints;
} else if ((i % 3 === 0) && (i% 5 ===0)) {
sum += pointsx;
} else if (i %3 ===0) {
sum += points3;
} else if(i%5 ===0) {
sum += points5;
} else {
sum += points1;
}
}
console.log(sum)
}
calculate(30);

Unbalanced tree from document.write and variable un-defined

I am writing a program to display total test grades and avg with a loop. however when I try to test it, I cant get the final message "Good Job" to show up and I am getting a error for unbalanced tree and undefined "Avg" variable. I dont see how "avg" is undefined when it works during the loop just not after
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do {
Testscore = prompt("Enter the test score ", 0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (avg > 80) {
document.write("Good Job!");
} else {
documet.write("Try harder..");
}
You just had a few typos in your code!
avg and Avg are different, as variables are case sensitive.
Additionally, there's a documet instead of document
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do
{
Testscore = prompt("Enter the test score ",0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (Avg > 80)
{
console.log("Good Job!");
}
else
{
console.log("Try harder..");
}

Categories

Resources