Sum values in javascript for loop [duplicate] - javascript

This question already has answers here:
Javascript prompt and alert inputting a number and it will loop and you will input numbers to get the average of it
(3 answers)
Closed 4 years ago.
How can I store all of my numberGrades values so they can included in my calculation, I"m new to this so if someone could update my code that would be perfect?
//user input number of grades to be entered
numGrades = prompt("Enter number of grades to be entered: ", ES);
//number of grades to be entered LOOP
for (index = 1; index <= numGrades; index++) {
numberGrades = prompt("Enter Grade " + index, ES);
}
//Calculation
gradePointAverage = numberGrades / numGrades;
document.write("Your GPA is " + gradePointAverage + PA);

prompt method returns a string, so you have to cast it to int or float using parseInt or parseFloat.
What you were doing is only getting the last value of your grades. What you want is to sum them all together THEN divide them by the number of grades
There are 2 solutions :
Store the inputs into an array
Sum them all together each time a user input a value
// First solution
// Create an array and append each value
numberGrades = [];
for (index = 1; index <= numGrades; index++) {
valuePrompt = prompt("Enter Grade " + index, ES);
numberGrades.append(parseFloat(valuePrompt));
}
//Calculation
sumOfGrades = numberGrades.reduce((a, b) => a + b, 0)
gradePointAverage = sumOfGrades / numGrades;
// Second solution
// Add every prompt by the user
numberGrades = 0;
for (index = 1; index <= numGrades; index++) {
valuePrompt = prompt("Enter Grade " + index, ES);
numberGrades += parseFloat(valuePrompt));
}
//Calculation
gradePointAverage = numberGrades / numGrades;

Related

Adding prompts to an array in javascript [duplicate]

This question already has answers here:
How to save prompt input into array
(5 answers)
Closed 7 months ago.
I'm busy with a task that requires me to ask the user to keep entering random numbers until the number is "-1". After that I would have to get the average of all the numbers entered excluding the "-1". I've gotten this far with it:
var userNumbers;
while (userNumbers !== "-1") {
userNumbers = prompt("Enter a number");
}
numbersArray = [userNumbers];
console.log(numbersArray);
Try this
// Store all numbers
const numbers = [];
let userNumber;
for(;;){
userNumber = prompt("Enter a number");
if(userNumber === '-1') { break; }
numbers.push(userNumber);
}
// Calculate average
let sum = 0;
let avg = 0;
numbers.forEach((value) => sum += value);
avg = sum / numbers.length

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 sum numbers from 1 through user's entry, using while-loop, do-loop?

I am trying to complete the following code to achieve the sum of numbers from 1 to 100(user's entry must be 1-100), using whileloop or doloop. I am new to this so, any help is much appreciated!
In the following code, I used prompt method to get the user entry. Wrote the code, to sum numbers; from 1 through the user's entry. I displayed the result in an alert box. Now, my challenge is I want to display an error message if the user's entry outside the 1-100 range. And after that, I do not want to do any calculations if user clicks cancel and stop displaying the prompt box.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
}
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
} while (counter<=numOfLoops)
alert ("sum=" +sum);
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
Simply move the calculation logic inside the condition where the user enters the correct input. This will make sure that the prompt closes automatically when you click on the cancel button (Prompt returns null when the user clicks on cancel)
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers != null && (isNaN(parseInt(numbers)) || parseInt(numbers) > 100 || parseInt(numbers) < 1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers != null) {
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum += counter;
counter++;
} while (counter <= numOfLoops)
alert("sum=" + sum);
}
</script>
You could simply use a do…while to solve your problem, e.g.:
let n = null;
do {
n = parseInt(prompt('Enter an int number between 1 and 100'));
} while (isNaN(n) || (n < 1 || n > 100));
let sum = n * (n + 1) / 2;
alert('The sum of all int numbers from 1 to ' + n + ' is: ' + sum);
N.B. The sum of the first n integer numbers can be computed as n * (n + 1) / 2, with O(1) complexity - reducing the O(n) complexity of your for loop.

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 + ".";

Average of input prompt numbers

I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<html>
<body>
<script type="text/javascript">
function show_prompt() {
i = 0;
do {
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);
</script>
</body>
</html>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number

Categories