Average of input prompt numbers - javascript

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

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 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.

How do you write a program in javascript that asks the user to enter a list of numbers, and then find the average of the numbers

I can't get this program to output the average of the entered prompted numbers by a user. How else should i code it? Any help will be appreciated.
var gpas = [];
var gp;
var total = 0;
let count = 0;
var max = 0;
var min = 0;
var out = "";
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(i);
}
}
for (var i = 0; i < gpas.length; i++) {
out += gpas[i];
out += "<br/>";
}
count++;
total += gpas[i];
var avg = total / count;
out += avg;
document.getElementById('output').innerHTML += out + "<br/>";
the output is showing "NaN" instead of a valid number.
You can only use a variable that holds the sum of the numbers entered and then just divide it by the total numbers entered.
First approach infinite loop :
The first approach acts as the one you're using. Basically, we'll ask for a new number as long as we don't get the string "XXX".
/**
* #const output the span where to print the average.
**/
const output = document.getElementById('output');
/**
* #var avg stores the sum of the entered numbers.
* #var i keeps track of the number of numbers entered.
**/
let sum = 0,
i = 0;
/** basically while true increment i **/
while (1 && ++i) {
/** ask for a number or "XXX" to exit **/
const n = prompt(`Enter a number or enter "XXX" to exit :`, 0);
/** if "XXX" is entered break the loop (the only way to break that infinite loop) **/
if(n == 'XXX') break;
/** if something else than "XXX" is entered try to cast it to a float **/
sum += parseFloat(n);
}
/** print the average **/
output.textContent = (sum / (i - 1)).toFixed(2); /** why dividing by "i - 1" and not only "i" is because "i" is incremented even when we enter "XXX" **/
<div>average: <span id="output"></span></div>
This approach is not user friendly (the loop can't be exited unless "XXX" is typed) and may consume a lot of resources.
Second approach fixed number of numbers :
This approach asks the user to enter how many number he want to type then we ask him to type as many numbers as the one he typed earlier.
const output = document.getElementById('output');
/**
* #var n the number of numbers the user is going to type.
* #var sum the sum of these numbers.
* #var i a counter used to exit the loop when we reach "n" nummbers typed.
**/
let n = prompt('How many element do you want to enter ?', 2),
sum = 0,
i = 0;
/** while i + 1 < n and no need to manually break the loop **/
while (i++ < n) sum += parseFloat(prompt(`Enter a number (${i} remaining) :`, 0));
output.textContent = (sum / n).toFixed(2); /** now we know how many numbers entered from the beging thanks to the variable "n" **/
<div>average: <span id="output"></span></div>
parseFloat used to parse the numbers (in fact they're strings) entered by the user to floats.
toFixed is used to have only two decimal numbers when calculating the average.
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(parseInt(i)); // we need string to number with `parseInt`
}
}
Thanks everyone that contributed. By applying some of the suggestions given, I was able to make it work. I also noticed that the code below does the work too:
var gpas = [];
var gp;
var out = "";
while (i != "XXX")
{
var i = prompt("Enter a gpa or XXX to Stop");
if(i != "XXX"){
gpas.push(parseInt(i));
}
}
let sum = gpas.reduce((a, b) => {
return a + b;
});
sum;
var avg = (sum/gpas.length);
document.getElementById('output').innerHTML += "average =" + avg + "<br/>";
</script>````

Factorial will not multiply

When I run the code it doesn't multiply my number it just outputs in a loop until it reaches 1
I have tried multiple different ways and this one is the closest i've gotten
......................................
var BR="<br />"; //html line break
function factorial(Num) {
document.write("The factorial of your number is" +Num +BR);
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
.........................................
It's supposed to take the number and multiply it down, so say you put in 20 it should go 19*18*17... down until it multiplies 1 and then outputs the product.
Place the document.write outside your function, and just print the result (Numfactorial) to the page. You also need to parse Num to a number, and remove var factorial:
var BR = "<br />";
function factorial(Num) {
if (Num == 1) return 1;
else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Enter a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of your number is " + Numfactorial + BR);
Well, that is the expected output of your code. Your function factorial is returning your value which you aren't using to display the value. You should instead write it like this:
....................................................
var BR="<br />"; //html line break
function factorial(Num) {
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
document.write("The factorial of your number is" +Numfactorial +BR);
.........................................

Sum of two numbers and the numbers between them

Ask user to enter a number. Then ask the user to enter a number bigger than the first number. Calculate a value that is the sum of all the numbers from the first number to the second number including the end points. For example, if the user enters 5 and 10 then calculate the total of 5 + 6 + 7 + 8 + 9 + 10. Display the results. MUST USE A WHILE LOOP
This is what I have so far. I can't seem to get the sum to be correct. If I enter the numbers from the example above, I get 49 instead of 45. I understand where I went wrong and why it is 49 based on my code but can't figure out how to make it correct.
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
// prompt user to enter two numbers
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
var number1 = Number(number1);
var number2 = Number(number2);
var start_point= number1;
var sum=0;
// display number1
document.write(start_point);
sum += start_point;
start_point++;
while (start_point <=number2) {
document.write(" + " + start_point);
sum += start_point;
start_point++;
}
// display sum
document.write(" = " + sum);
Welcome to StackOverflow!
The cause of error is at this part of the code
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1; // you are already increasing the middlePoint number
counter++;
middlePointSum += middlePoint;
}
Therefore, the sum is always over by the number of counter - 1. What you should have done, is execute middlePointSum += middlePoint; first before increasing the value of middlePoint and counter.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
counter++;
}
This code should work for you. Variabel sum should contain your desired sum.
var sum = 0;
var firstNumber = 0;
var secondNUmber = 0;
var firstNumberStr = '';
var secondNUmberStr = '';
// prompt user to enter two numbers
firstNumberStr = prompt("Enter first number: ");
while(isNaN(firstNumberStr)){
firstNumberStr = prompt("Enter Correct first number: ");
}
secondNUmberStr = prompt("Enter a number bigger than first number: ");
while(isNaN(secondNUmberStr) || parseInt(firstNumberStr) >= parseInt(secondNUmberStr)){
secondNUmberStr = prompt("Enter a number bigger than first number: ");
}
firstNumber = parseInt(firstNumberStr);
secondNUmber = parseInt(secondNUmberStr);
while(firstNumber <= secondNUmber){
sum += firstNumber;
firstNumber++
}
You did a very small mistake in the code . The bug is in while loop.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
you are incrementing the middlepoint before middlePointSum is Calculated. It should be incremented after calculating the middlePointSum.
while (counter < difference) {
document.write(" + " + middlePoint);
counter++;
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
}
Your middlePointSum is starting from 1 intead of 0 so you got: 5 + (7 + 8 + 9 + 10) + 10 to fix your code set middlePointSum to INITIAL_VALUE
For simplification just ignore the difference between the numbers, increment number1 until you reach number 2
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
var incNumber;
var strResult = [];
number1 = incNumber = Number(number1);
// use incNumber if you need to preserve number1 value or just use number 1 value instead
number2 = Number(number2);
var sum = 0;
while(incNumber <= number2) {
strResult.push(incNumber);
sum += incNumber++;
// this means add incNumber to sum then increment it by 1
}
document.write(`${strResult.join(' + ')} = ${sum}`);
One problem is that your middlePointSum does not take into account the first number after the number1, for example, the 6 in your example. Another problem is that your counter < difference test is inaccurate - you would have to iterate until counter + 1 < difference:
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
middlePointSum = middlePoint;
while (counter + 1 < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
console.log(middlePointSum);
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
But this seems far, far more complicated than it needs to be - why not simply iterate from number1 to number2, adding to sum along the way?
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
document.write(number1);
let sum = number1;
for (let i = number1 + 1; i <= number2; i++) {
sum += i;
document.write(' + ' + i);
}
document.write(' = ' + sum);
Or, create an array of the numbers, join by plus signs, and calculate the sum with reduce:
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
const nums = Array.from(
{ length: number2 - number1 + 1 },
(_, i) => i + number1
);
const sum = nums.reduce((a, b) => a + b);
document.write(nums.join(' + ') + ' = ' + sum);
var num1 = Number(prompt("Enter a number"));
var num2 = Number(prompt("Enter a larger number"));
document.write(num1 + "+" + num2 + "=" + (num1+num2));
// now lets find the sum of numbers between these two numbers.
document.write("<br>"); // new line
var counter = num1; // we will start countring from the smaller number
var sum = 0;
//keep looping until we reach the bigger number (num2)
while(counter<=num2) {
sum += counter;
// print the current number
document.write(counter);
//print a plus sign
if(counter<num2) {
// only put a (plus sign) if we are not yet reached num2
document.write("+");
}
//increment to control the loop
counter ++;
}
//finally put the result
document.write("=" + sum);
You are setting counter to the constant COUNTER_VALUE which is 1.
Then, in your program, you are entering 5 and 6 as input. The difference is 6-5 which is 1.
Your while loop has a condition to only execute when counter<difference . In your case, counter=1 and difference=1. This means that they are equal, and thus, the loop will not execute.
I hope this sheds light on what needs to be done from your side to fix this bug.

Categories