Javascript find average from user's input - javascript

I know there are similar questions on here to mine but I don't see the answer there.
Where am I going wrong with this JS code to find the average number from the user's input?
I want to keep entering numbers until -1 is entered. I think -1 is being counted as an input/
var count = 0;
var input;
var sum = 0;
while(input != -1){
input = parseInt(prompt("Enter a number"));
count++;
sum = sum + input;
sum = parseInt(sum);
average = parseFloat(sum/count);
}
alert("Average number is " + average);

This is the right order (without all the unnecessary parsing...)
var count = 0;
var input;
var sum = 0;
input = parseInt(prompt("Enter a number"));
while (input != -1) {
count++;
sum += input;
average = sum / count;
input = parseInt(prompt("Enter a number"));
}
alert("Average number is " + average);
DEMO
Note that you can calculate the average once outside of the loop and save some CPU.

You need to check after you take the input from the user.
while(input != -1){
input = parseInt(prompt("Enter a number"));
//The user enters -1 but still inside the while loop.
if(input != -1)
{
count++;
sum = sum + input;
}
sum = parseInt(sum);
average = parseFloat(sum/count);
}

Here is the function code you need.
var count = 0;
var input;
var sum = 0;
while(true){
input = parseInt(prompt("Enter a number"));
if(input != -1)
{
count++;
sum = sum + input;
sum = parseInt(sum);
}
else
break;
}
average = parseFloat(sum/count);
alert("Average number is " + average);

This will grab the average...Simply accumulate the values and then divide the total 'sum' by the number of 'inputs made'(in our case we just use the count++)
var count = 0;
var input;
var sum = 0;
while(input != -1){
count++;
input = prompt("Enter a number");
sum += input;
sum = parseInt(sum);
}
average = (sum/count);
alert("Average number is " + average);

Related

How to swap first and last digits of a number using for loop in Javascript

I need to ask user to input a 3 digit number and then swap the first and last numbers using a for loop. This is what I have so far, but I'm stuck. Using a for loop seems illogical, but that is what I have to do:
num = prompt("Please input a number with 3 digits.");
let firstDigit = num[0];
let secondDigit = num[1];
let lastDigit = num[2];
for (firstDigit < 10; secondDigit < 10; lastDigit < 10); {
console.log(lastDigit + secondDigit + firstDigit);
}
Please help!
Thanks
is it help for you?
// let num = prompt("Please input a number with 3 digits.");
// if (num.length > 3) alert("3 digits please");
// else {
// let answer = "";
// for (var i = 2; i >= 0; i--) {
// answer = answer + num[i];
// }
// console.log(answer);
//}
let num = prompt("Please input a number");
let temp = "";
let answer = "";
for(let i = 0 ; i < num.length; i++) {
if (i === 0) temp = num[i]; // save first number to temp
else if (i === num.length - 1) {
// When the last number is encountered, the last number is put at the beginning, and the first number stored in temp is put at the end.
answer = answer + temp;
answer = num[i] + answer;
}
else answer = answer + num[i];
}
console.log(answer);

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);

Calculate the sum of positive values smaller or equal to a number

I am trying to calculate the sum of positive values smaller or equal to the entered number, for ex: 5 -> 1+2+3+4+5 = 15
I came up with this:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do {
sum = sum += i;
i--
document.write(sum);
} while (i > 0);
I don't understand what I am doing wrong.
i think this is correct code:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do
{
sum += i;
i--;
}
while (i > 0);
document.write(sum);
and i suggest you to use this formula : document.write((num * (num + 1)) / 2);
If you look closer to your task, you'll find out, that:
If Num = 1, the sequence to be summed is [1]
if Num = 2, the sequence is [1, 2]
if Num = 3, the sequence is [1, 2, 3]
You can imagine, that you have a square with sides equal to num, for example, when num = 4:
****
****
****
****
And you need to summ 1, 2, 3, 4:
***#
**##
*###
####
See? It's a square of a triangle.
It could be calculated by formula: num * (num + 1) / 2
So, you code could be:
var num = Number(prompt("Enter a number "));
document.write(num * (num + 1) / 2)
You are writing the sum on each loop instead you have to print it finally. If you want to print the numbers then keep it an array and join them with + symbol before writing. To make it in ascending order change the loop condition.
var num = Number(prompt("Enter a number "));
sum = 0;
i = 1;
nums = [];
do {
sum = sum += i;
nums.push(i++);
}
while (i <= num);
document.write(nums.join(' + ') + ' = ' + sum);
Do with increment instead of decrements.And also show result of sum outside of loop .Not with in loop.And create array to append increment value.Finally print with document.write
var num=Number(prompt("Enter a number "));
sum = 0;
i = 1;
var a=[];
do {
sum +=i;
a.push(i)
i++;
}
while (num >= i);
document.write(a.join('+')+'='+sum)
You should write the answer at the end of loop and make this simple sum += i;.
var num = Number(prompt("Enter a number"));
sum = 0;
i = num;
do {
sum += i;
i--;
}
while (i > 0);
document.write(sum);
var number = 5, // Your number
result = 0;
while ( number !== 0 ) {
result += number;
number--;
}
document.write(result);
Fast and precious solution.
Here is the case with complete check and display as you need: JAVA
public static void main ( String arg[]) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
System.out.println("Number entered : " + number);
int sum =1 ;
if(number > 1) {
int nextNumber = 1;
System.out.print(nextNumber);
do {
// sum of all the positive numbers
nextNumber++ ;
sum = nextNumber + sum;
System.out.print( " + " + nextNumber);
}while(nextNumber < number);
System.out.print(" = " + sum);
}
}
var num = Number(prompt("Enter a number"));
sum = 0;
for (i = num; i > 0; i--) {
sum += i;
}
document.write(sum);

Beginner - While Loop sum all user inputs under 50 - Javascript

I am still a beginner on Javascript and I have a question.
I would like to sum all user inputs under 50 if written 0 to stop the program and display their amount
By example:
First Number 5, Second number 3, Third Number 55, Fourth Number 0. (The program will print 8)
var userInput = parseInt(prompt('Write Number'));
while(userInput!=0) {
var userInput = parseInt(prompt('Try Again!'));
if(userInput < 50){
var sum = userInput + userInput;
}
document.write(sum + '<br>');
}
Thanks a lot
loop and add previous value if condition match :
var inputData = Number(prompt("Enter the input number"));
var finalOutput=0;
while (inputData > 0) {
if (!(inputData > 50)) {
finalOutput += inputData;
}
inputData = Number(prompt("Enter the input number"));
}
document.write("SUM is : " + finalOutput);
You'd do this:
var input = Number(prompt("Enter a number"));
var output = 0;
while (input > 0) {
if (!(input > 50)) {
output += input;
}
input = Number(prompt("Enter a number"));
}
document.write("The sum of all the numbers lower than 50 was " + output);

Finding the factorial using a loop in javascript

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);

Categories

Resources