Adding prompts to an array in javascript [duplicate] - javascript

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

Related

Why doesn't my JavaScript program to find odd numbers work? [duplicate]

This question already has answers here:
Javascript string/integer comparisons
(9 answers)
Sum of two numbers with prompt
(10 answers)
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I made a simple js code to input start value and end value form prompt and then find all the odd numbers, unfortunately it's not working properly. when i input 1 and 10 it'll work, but when i input 5 for sValue(start value) the program won't work. any idea?
var odd = [];
var sValue = prompt("start");
var eValue = prompt("end");
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);
Because the value of prompt is a string. You need to convert it to a number with parseInt(v, 10).
var odd = [];
var sValue = parseInt(prompt("start"), 10);
var eValue = parseInt(prompt("end"), 10);
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);

JavaScript sum of numbers in an array producing string instead of numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 2 years ago.
The code below is outputting a string of numbers instead of the sum of the numbers in the array. For example, if n is set to 3 and the numbers 1 2 3 are added to the array the output is 0123 when I need it to be 6. I can only use while loops and not for loops for this which is why the code looks slightly odd. Can someone please explain to me why the output is a string and not the sum of the numbers?
var n = -1;
var n2 = 0;
var numbers = [];
while (n < 0) {
n = prompt("Please enter a positive interger");
}
while (n > 0) {
n2 = prompt("Please enter a interger");
numbers.push(n2);
n = n - 1
}
var sum = numbers.reduce(function(a, b){
return a + b;
}, 0);
alert(sum);
All you need to change is where you push the numbers to the array from
numbers.push(n2);
to
numbers.push(parseInt(n2, 10));
because the prompt believes always that the user inserts a string.
var n = -1;
var n2 = 0;
var numbers = [];
while (n < 0) {
n = prompt("Please enter a positive interger");
}
while (n > 0) {
n2 = prompt("Please enter a interger");
numbers.push(parseInt(n2, 10));
n = n - 1
}
var sum = numbers.reduce(function(a, b){
return a + b;
}, 0);
alert(sum);
Prompt always return a string. You have to parse it:
strN = prompt("Please enter a positive interger");
n = parseInt(strN);

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

Sum values in javascript for loop [duplicate]

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;

get always 10 numbers from randoms - Javascript [duplicate]

This question already has answers here:
Want to produce random numbers between 1-45 without repetition
(4 answers)
Closed 4 years ago.
I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:
for(let j = 1; j <= 21; j++) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.
I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...
let s = new Set();
while (s.size < 10) {
s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}
console.log([...s]);
You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:
const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)
while (array.length < 10) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
console.log(array);

Categories