0

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

4
  • It looks like all you need to do is break your work up into two loops instead of one. What's the problem? Commented Oct 6, 2020 at 21:38
  • I guess im not sure how to do that as im more familiar with for loops, any ideas on how i would go about it? Also how would I add user inputs instead of the place holder 1,2,3,4,5 Commented Oct 6, 2020 at 21:39
  • Have you looked the the documentation for a while loop? Also, think about how you input information into a web page when you need to do it on someone else's page and then do some research on that. We are here to help, but we have guidelines for asking questions an d we expect that you'll do you research before posting. Commented Oct 6, 2020 at 22:14
  • Please be specific: What exactly is going wrong? Commented Oct 8, 2020 at 23:10

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.