How do I add values of a prompt together? - javascript

I'm supposed to prompt the user to enter a string of numbers separated by spaces and alert the sum of those numbers. I'm trying to get the values into an array and then add them up, but it's not working. I've tried a ton of different ways. Help please!
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = new Array (input.split(" "));
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += numbers[i];
};
alert(sum);
JSFiddle: http://jsfiddle.net/mUqfX/2/

You're close, 2 issues with your code. First, .split returns an array so you don't need to wrap a new around it. Second, you need to parse the number otherwise your joining strings together. Try
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);

You have 2 problems:
input.split(" ") returnss an array, so you don't need to place it in another array
Your numbers array contains strings, which you need to coerce to numbers to total them.
Try this:
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);

Related

I want to prompt the sum of the numbers prompted before

I am stuck.
I have to prompt a number. and then to create a cycle of prompts related with the intiial prompt and then sum them. I am completely lost. how can I sum them?
let first_question=prompt("introduce the quantity of numbers you want to sum")
for (let i=0; i < first_question;i++)
{
let second_question= prompt ("introduce the number you want to sum");
}
do something like this:
var first_question = parseInt(prompt("Introduce the quantity of numbers you want to sum: "));
var sum = 0;
for (let i = 0; i < first_question; i++) {
let second_question = parseInt(prompt("Introduce the number you want to sum: "));
sum += second_question;
}
and at the end the variable sum will have the value you want.
Also note that prompt() will return a string, so I used parseInt() in order to transform it into a number

how to sum integer from htmlelement

I am trying to get the innerHTML of all elements with classname "money" and sum it. But when I am retrieving it with my code it will place all the digits next to eachother.
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i=0; i< arr.length; i++){
var val = elements[i].innerHTML;
console.log(val);
total += parseFloat(val).toFixed(2)
}
console.log(total);
The result I'm getting is the following:
image of result
How can I solve this?
toFixed() is converting a number to a string. So you add strings which leads to concatenating.
Sum everything and use toFixed() after you have the final value or use Math.round()
toFixed() returns a string. Parse it (with a unary plus operator), then add to total:
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i = 0; i < arr.length; i++) {
var val = elements[i].innerHTML;
console.log(val);
total += +parseFloat(val).toFixed(2)
}
console.log(total);
<div class="money">100</div>
<div class="money">200</div>
<div class="money">300</div>

Sum and Average of a series of numbers inputed to a text field

I am trying to create an application that calculates the sum and average of numbers that are inputted into a text field separated by spaces.
I am stuck on the part where you have to put in a loop to calculate the sum and avg from the spaced inputs. I have been using console.log to test throughout while I type my code.
Any guidance would be helpful. First time doing javascript. I have looked at the forms on this website and it seems like all the sum/avg javascript questions arent input text based. That is why I am creating a new question.
HTML and Javascript is Below
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
Javascript
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}
// Here is your function:
/*function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}*/
// Here is a way to do it functionally:
function calculateSumAverage() {
// This is the string that contains the numbers separated by a space.
var inputValue = document.getElementById('numberSeries').value;
var values = inputValue.split(' ')
.map((val) => parseInt(val))
.filter((val) => !isNaN(val));
var sum = values.reduce((currentVal, nextVal) => currentVal + nextVal, 0);
document.getElementById('calculationOutput').innerHTML = `Average: ${sum / values.length}`;
}
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
You code is fine except sum += parseInt(arr[i]); you need to parse each string input to integer
input type="text" will give a string.Also to split this string ,use var arr = numberSeries.split(""); , note there is no space between the quotes. To convert each string to number use unary operator.
sum += +arr[i]; The plus(+) sign before arr[i] will convert a string to number.Unless you convert to number , the string concatenation will produce like this 0123...
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split("");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
console.log(arr)
//loop input array and sum
for (var i = 0; i < arr.length; i++) {
sum += +arr[i];
}
console.log(sum);
}
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
Try like this
function calculateSumAverage()
{
var numberSeries = document.getElementById("numberSeries").value;
var arr = numberSeries.split("");
var sum = 0;
var avg = 0;
for (var i = 0; i < arr.length; i++)
{
sum += parseInt(arr[i]);
}
}

How can I make my output appear all on one line with no spaces?

I have a simple Javascript problem that I'm working on, where the point is to...
Take an input, like 123
Separate the input as single digits, then square those single digits, thus getting 149.
Display that "149" (in this case) as an output.
I don't know how to display it as 149. I can only show it as
1
4
9
Sure, I might try adding it to an array then for looping the results... something tells me that this is the slow solution, and that there is a faster one. Here's my code.
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
console.log(newnum);
}
}
squareDigits(123);
Create empty array outside of the loop
Add squares of the each digit in the array
Join the array after loop finishes
function squareDigits(num) {
num = '' + num;
var len = num.length;
var squares = []; // Define empty array
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
squares.push(Math.pow(digit, 2)); // Push the square of the digit at the end of array
}
return squares.join(''); // Join the array elements with empty string as glue
}
var squares = squareDigits(123);
console.log(squares);
document.write(squares);
By string concatenation
Declare a empty string before the for loop
Concatenate the square of the digit to the string by first casting the number to string
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum = ''; // Decalare variable with Empty string
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum += '' + Math.pow(digit, 2); // Cast the square to string and then concatenate to the string
}
return newnum; // Return the string
}
var squares = squareDigits(123);
document.write(squares);
Try utilizing String.prototype.split() , Array.prototype.map() , Array.prototype.join()
function squareDigits(num) {
return String(num).split("")
.map(function(n) {
return Math.pow(n, 2);
}).join("");
}
console.log(squareDigits(123));
What about this?
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
var digits = '';
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
digits += '' + newnum
}
console.log(digits);
}
try process.stdout.write, as in
process.stdout.write(newnum);

how to add array element values with javascript?

I am NOT talking about adding elements together, but their values to another separate variable.
Like this:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.
How should I write what I want ?
Thanks
Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.
A quick way is to use the unary plus operator to make them numeric:
var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
TOTAL += +myArray[i];
}
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)
var total = 0;
for(i=0; i<myArray.length; i++){
var number = parseInt(myArray[i], 10);
total += number;
}
Use parseInt or parseFloat (for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);

Categories

Resources