Nested if/else in While loop - javascript

I'm trying to make a program that determines if a grade entered is passing or failing. It stops when the user enters -1. Once the user does enter -1, it has to print out the average of the passing scores and the total amount of scores. It's not really working correctly though. What am I doing wrong?
var countTotal=0; //variable to store total grades.
var countPassing=0; //variable to store total passing scores.
var x= 0; //variable to contain sum of all passing scores.
var grade=parseInt(prompt("Please enter a grade."));
while (grade != (-1*1))
{
if (grade > 65) {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is failing.<br>");
}
countTotal++;
}
//Loop ends
document.write("Total # of grades: " + countTotal); //Prints out total # of passing scores.
document.write("Passing average: " + ((x)/(countPassing))); //Prints out average of all passing scores.

Try working through it by hand. The user enters the very first grade. Then the loop starts. Immediately, you ask for a new grade, discarding the first one. If you move the prompt down to the end of the loop, it should work. Like this:
while (grade != (-1*1))
{
if (grade > 65) {
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
document.write(grade + " is failing.<br>");
}
grade=parseInt(prompt("Please enter a grade."));
countTotal++;
}

Related

Calculator for test scores javascript

I'd like to create an average calculator for test scores. Have the user enter numbers. They can enter as many as they want. Once they enter “-1”, end the program. Display the lowest test score, the highest test score, the sum of all test scores, and the average of all test scores.
The following is my code. I've already figured out how to do the sum of the scores. However, I don't know how I can turn ALL my inputs into a string - possibly output the lowest (Math.min), highest (Math.max) and average of the test score.
I tried joining strings together but in the end I couldn't figure out how to work!
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
var item = itemGrade + ", "
total += itemGrade;
if (itemGrade == -1) {
break;
}
}
document.write("Total: " + total)
Here is a short piece of code that should do the job. The syntax ${variable} with ` allows variables to become strings. Total score is how you've written it. Lowest and highest simply checks if the new score entered is a higher or lower number and replaces the variable as the new lowest/highest. A count is added to calculate the average of all scores.
var total_score = 0.0;
var average_score = 0.0;
var lowest_score = Infinity;
var highest_score = 0.0;
var count = 0.0;
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
if (itemGrade == -1) {
break;
}
total_score += itemGrade;
if (lowest_score > itemGrade){
lowest_score = itemGrade;
}
if (highest_score < itemGrade){
highest_score = itemGrade;
}
count++;
}
average_score = total_score/count;
document.write("Total Score: " + `${total_score}`);
document.write("Average Score: " + `${average_score}`);
document.write("Lowest Score: " + `${lowest_score}`);
document.write("Highest Score: " + `${highest_score}`);
var item = []
item.push(itemGrade)
You can create an empty array and use push() inside the while loop to add value to end of an array or use unshift() in case you want to add in starting position of the array

How to get a JavaScript factorial programs' loop to show the working used?

Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}

I'm trying to find the highest mark and lowest mark in an array with prompts

So my teacher assigned us an assignment to make a program to find the highest and lowest mark of a maximum of 15 students. So it's possible to put in less than 15 students. The user must input the student's name and after the student's mark. After all the student's names and marks have entered, it's suppose to compare the marks to find the least and the greatest.
CODE:
var Students = ["sn1", "sn2", "sn3", "sn4", "sn5", "sn6", "sn7", "sn8", "sn9", "sn10", "sn11", "sn12", "sn13", "sn14", "sn15"]; //student's name array
var Marks = ["sm1", "sm2", "sm3", "sm4", "sm5", "sm6", "sm7", "sm8", "sm9", "sm10", "sm11", "sm12", "sm13", "sm14", "sm15"]; //student's marks array
Students[0] = prompt("Student 1's name.");
if(Students[0].length == 0) {
Marks[0] = null
} else {
Marks[0] = prompt("Student 1's mark."); //I just copied and pasted this 15 times and changed the [0] to the next number.
while(isNaN(Marks[0]) || Marks[0] >= 101 || Marks[0] <= -101) { //if number is greater than or equal to 101, or less than or equal to -1. Prevents a mark higher than 100 and less than 0.
window.alert("Please input a number between 0-100.");
Marks[0] = 0
Marks[0] = prompt("Student 1's mark."); //reprompt.
}
}
console.log(Students[0] + " " + Marks[0]); //displays mark.
var greatest = -100; //my friend did this part so I don't know if it's right.
var least = 100;
var trackg = 0;
var trackl = 0;
if (Marks[x] != null){ //if this isn't here then I get an error with null.length can't be measured below.
for(var x = 0; x < Marks.length; x ++) {
if(Marks[x].length == 2) {
" " + Marks[x];
}
if(Marks[x] >= greatest && Marks[x] != null) {
greatest = Marks[x]
trackg = x
}
}
}
for(var j = 0; j < Marks.length; j ++) { //the marks[x] != null doesn't work here. it will show that the greatest number is the least number as well which it isn't.
if (Marks[j] <= least && Marks[j] != null){
least = Marks[j];
trackl = j;
}
}
console.log(Students[trackg] + " has the highest mark of " + Marks[trackg] + ". " + Students[trackl] + " has the lowest mark of " + Marks[trackl] + ".");
PROBLEMS:
1. When it compares the number it just takes the first number as the largest number and that's it. So lets say I put the first student's mark as 99 and after I put the 2nd student's as 100. It says 99 is the highest mark and same with negatives for the lowest.
2.I also get that if I put in 100, numbers like 29, 99, etc are higher numbers due to 1 < 2 or 9 etc.
3.For negative numbers, If I put -13 and -99, -13 says it's the lowest which it isn't.
Also, if I put in 10 and 100 (even as negatives), 10 is greater/ the least.
I've tried so many things and I don't know whats wrong. (Btw this is my first time with javascript). This assignments due Monday. Thanks ;A;
This is an example of how you could do it. Note how the validation is done, and conversion of user input to an actual number for comparison. Only one main loop is necessary; the while loops are to ensure the user enters valid data.
You do not need to actually store all the students' data as an array to display the highest and lowest result.
var students = [];
var numOfStudents, highest = { mark:-1 }, lowest = { mark:101 };
// Get number of students between 1 and 15
while (isNaN(numOfStudents) || numOfStudents <= 0 || numOfStudents > 15)
numOfStudents = parseInt(prompt('How many students? (1-15)', '1'), 10);
// For each student, get the name and mark
for (i = 1; i <= numOfStudents; i++) {
var student = {};
while (typeof student.name === 'undefined' || student.name == '')
student.name = prompt('Enter Student '+i+' name:', '');
while (typeof student.mark === 'undefined' || isNaN(student.mark) || student.mark < 0 || student.mark > 100)
student.mark = parseFloat(prompt('Enter Student '+i+' mark (0-100):', ''));
// Check if highest or lowest
if(student.mark > highest.mark) highest = student;
if(student.mark < lowest.mark) lowest = student;
// Save current student to the list (optional)
students.push(student);
}
// Display result
document.body.innerHTML = highest.name + " has the highest mark of " + highest.mark + ". " + lowest.name + " has the lowest mark of " + lowest.mark + ".";

JavaScript Find average from user input

I am having trouble calculating the mpgTotal. This should add together all of the mpgTankful and divide them by how many are added together (essentially finding the average of mpgTankful). I tried implementing a counter but It's not turning out how I'd like it to. It should keep counting until a user enters -1 to quit.
A sample result would be:
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case mpgTankful would be divided by 1)
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case add previous mpgTankful with current mpgTankful and divide by 2)
Miles user entered:
Gallons user entered:
mpgTankful:
mpgTotal: (in this case add first mpgTankful with second and current (third) mpgTankful and divide by 3)
var miles, //Miles driven
gallons, //Gallons used
mpgTankful, //MPG this tankful
mpgTotal, //Total MPG
mi, //Miles driven converted to integer
gal, //Gallons used converted to integer
count=0,
avg;
//Enter -1 to quit
while(miles!="-1"){
//Read in the Miles Driven from user as a String
miles=window.prompt("Enter miles (-1 to quit):");
if(miles=="-1"){
break;
}
//Read in the Gallons used from user as a String
gallons=window.prompt("Enter gallons:");
//Convert numbers from Strings to Integers
mi=parseInt(miles);
gal=parseInt(gallons);
//Calculate the MPG Tankful
mpgTankful=mi/gal;
//Calculate the Total MPG
mpgTotal+=mpgTankful;
count++;
if(count!=0){
avg=mpgTotal/count;
}
else
avg=0;
document.writeln("avg: " + avg);
//Print Results
document.writeln("<br/><br/>Miles driven: " + mi +
"<br/>Gallons used: " + gal +
"<br/>MPG this tankful: " + mpgTankful +
"<br/>Total MPG: " + mpgTotal);
}
You were almost there...
mpgTotal+=mpgTankful; can't work: the first time this is called, mpgTotal === undefined
The if(count!=0) is useless.. you incremented count one line above...
You calculated avg but didn't output it (according to the description for 'Total MPG: '): <br/>Total MPG: " + mpgTotal
For this example I added a looping check for invalid input (explanations in comments).
<script>
var miles=0 //Miles driven
, gallons=0 //Gallons used
, mpgTankful=0 //MPG this tankful
, mpgTotal=0 //Total MPG
, mi=0 //Miles driven converted to integer
, gal=0 //Gallons used converted to integer
, count=0
, avg=0
; // end vars
main: while(true){ //main loop, labeled 'main'
if( (miles=prompt('Enter miles ("-1" to quit):')) === '-1' )
break main; //well.. plain english..
if( isNaN(mi=parseInt(miles, 10)) ){ //check if we get a number
alert('Please enter a number or enter "-1" to quit.');
continue main;
}
while(true){
if( (gallons=prompt('Enter gallons ("-1" to quit):')) === '-1' )
break main; //NOT this inner loop.
if( isNaN(gal=parseInt(gallons, 10)) ){ //check if we got a number
alert('Please enter a number or enter "-1" to quit.');
//no need to instruct a continue for this loop..
} else break; //this inner loop (so we can go on with 'main' below).
}
mpgTankful=mi/gal; //Calculate the MPG Tankful
mpgTotal+=mpgTankful; //Calculate the Total MPG
avg=mpgTotal/++count; //Calculate avg (and pre-increment count)
//Print Results
document.writeln( '<br/><br/>Miles driven: ' + mi
+ '<br/>Gallons used: ' + gal
+ '<br/>MPG this tankful: ' + mpgTankful
+ '<br/>Total MPG: ' + avg
);
}
document.close(); //don't forget to close the body..
</script>
This should get you started.

How to generate a random number only once, and reuse its output?

I'm learning programming starting with Javascript, and my instructor had us doing a random dice roll, a simple Math.ceil(6*Math.random())
I was trying to slightly gameify it and judge the result. So, if you roll a 7, you win, any other roll you lose. The ultimate result would be,
"You rolled a: 7
You win!"
However, I attempt to accomplish by saying approximately:
console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose. Better luck next time");
}
diceSum() function evaluates each time, so I may get "You rolled a: 7" and "Aw... you lose" because the first roll was a 7, but by the time the if statement came in, the diceSum was something different.
How do I generate a random number like a dice roll and then reuse its value over and over?
Here's my current code (there is far more than necessary because I'm trying to display the values so I know if it is returning the correct answer):
//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
return Math.ceil(6*Math.random());
};
//Sum up two dice rolls
var diceSum = function() {
var firstDie = getDieRoll();
var secondDie = getDieRoll();
return firstDie+secondDie;
};
//
//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose. Better luck next time."
//
//Outputs
//show total sum to compare with message below
console.log(diceSum())
//Return a message stating the result
console.log("You rolled a " + diceSum())
//View true false status to compare with message returned below
console.log(diceSum()==7)
//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
You put the result in a variable, and use the variable:
var sum = diceSum();
//Outputs
//show total sum to compare with message below
console.log(sum);
//Return a message stating the result
console.log("You rolled a " + sum)
//View true false status to compare with message returned below
console.log(sum == 7);
//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
By the way, the way to calculate the random number is wrong. The random method is defined to return a value that is 0 <= n < 1, i.e. it can be zero, but it can never be one.
If you use Math.ceil, the effect is that the result will occasionally be zero, and the chance to get a six is slightly smaller than the other numbers.
Use Math.floor instead:
function getDieRoll() {
return Math.floor(6 * Math.random()) + 1;
};
Save it to a variable:
var sum = diceSum();
console.log("You rolled a " + sum);
if (sum == 7) {
console.log(winMsg);
} else {
console.log(loseMsg);
}
Or:
var sum = diceSum(),
msg = sum == 7 ? winMsg : loseMsg;
console.log("You rolled a " + sum);
console.log(msg);

Categories