Reputation: 1
I need to write a code that will prompt the user for five integer numbers and then determine the product and sum of the values.
It needs to use an array to enter the values, use a for loop to display the numbers and product, a while loop to display numbers and their sum, and then an HTML line that will display "the sum of x y and z is: sum and the product of x y and z is: product". I have this so far, can anyone help me out?
var array = [1, 2, 3, 4, 5, 6],
s = 0,
p = 1,
i;
for (i = 0; i < array.length; i += 1) {
s += array[i];
p *= array[i];
}
console.log('Sum : '+s + ' Product : ' +p);
Upvotes: 0
Views: 69
Reputation: 56754
Using ECMAScript 6, here's one way to do this:
let numbersToEnter = 5;
let numbersEntered = [];
while (numbersToEnter) {
numbersEntered.push(parseInt(prompt(`Enter a number, ${numbersToEnter--} to go:`)));
}
// filter out non-numbers
numbersEntered = numbersEntered.filter(n => !isNaN(parseInt(n)));
const sum = numbersEntered.reduce((acc, val) => acc + val, 0);
const product = numbersEntered.reduce((acc, val) => acc * val, 1);
console.log(`You entered these numbers: ${numbersEntered}`);
console.log(`Sum is ${sum}`);
console.log(`Product is ${product}`);
Upvotes: 1