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..");
}
Related
I'm fairly new to coding and have this practice that I can't figure out the last part of it.
I'm rolling three dice and supposed to count how many combined value of sevens I get at 1000th roll.
Do I have to create an array? the hint given to me was to create a counter variable. But I can't find any solution. I know it must be something simple. I need your guidance!
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("Value of Dice 1 is " + diceOne);
console.log("Value of Dice 2 is " + diceTwo);
console.log("Value of Dice 3 is " + diceThree);
console.log("The Sum of the Dice is " + diceSum);
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
}
}
If you need to count the times the 3 dice add up to 7, you can create a variable to keep track of this.
Inside your loop, you increase this by one everytime diceSum is 7.
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
var sevenCount = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("The Sum of the Dice is " + diceSum);
if(diceSum === 7){
sevenCount = sevenCount + 1;
}
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
console.log("The seven count is " + sevenCount);
}
}
They're teaching you something that's actually really good to know.
You don't have to remember all values in order to calculate the average or number of 7s. You only have to count how many 7s you've seen and keep another variables that's the sum of all the values you've seen.
Edit: if you want to count the number of 7s you've seen, you need to create a variable, say count_7s and every time you see a 7, you increment count_7s = count_7s + 1.
You need no roll count, because you loop the same amount, and you need a counter for sevens. An you could take a variable for sum and calculate later the average. This is better in terms of numerical precision.
At the end show the result of average and count of sevens.
var getRandomInt = function(x) {
return Math.floor((Math.random() * x) + 1);
},
sum = 0,
average = 0,
sevens = 0;
for (var i = 1; i <= 1000; i++) {
let diceSum = getRandomInt(6) + getRandomInt(6) + getRandomInt(6);
sevens += diceSum === 7;
sum += diceSum;
}
average = sum / 1000;
console.log("The Average is " + average);
console.log("The Count of Sevens " + sevens);
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.
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);
function start() {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < 12){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
I was told I am not allowed to hardcode the statement, how to I go about changing the 'while' statement so I am not hardcoding?
Probably they mean
var arr = new Array(12);
var randIndex=0;
while(randIndex < arr.length){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[randIndex] = randomnumber;
randIndex++;
}
Looks like a school assignment. If you are not supposed to hardcode the number of elements in array (currently 12) then you will need to get that number from user in some way. Or alternatively use a random number as shown below.
Note: there is a catch if you let the user specify the number of elements. I'll keep it for you to explore and fix.
function start(len) {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < len){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
// start(10); // you can get the number of elements in array from user and pass it here. I'm passing hardcoded 10 for now.
start(Math.ceil(Math.random()*20)); // alternatively passing a random number
<div id='msg'>
</div>
I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.
How can I stop i reaching inputNumber?
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i <= inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
here is an error i <= inputNumber
should be i < inputNumber
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
you can keep this:
i <= inputNumber
and just do this change:
total = total * i;
then the code snippet would look like this:
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 1; i <= inputNumber; ++i){
total = total * i;
}
console.log(inputNumber + '! = ' + total);
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
alert(inputNumber + '! = ' + total);
You could use the input value and a while statement with a prefix decrement operator --.
var inputNumber = +prompt('Please enter an integer'),
value = inputNumber,
total = inputNumber;
while (--value) { // use value for decrement and checking
total *= value; // multiply with value and assign to value
}
console.log(inputNumber + '! = ' + total);
Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:
var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
total *= i;
}
console.log(total);
function factorialize(num) {
var result = num;
if(num ===0 || num===1){
return 1;
}
while(num > 1){
num--;
result =num*result;
}
return result;
}
factorialize(5);