0

I am currently working on a 1/2 pyramid of numbers. I can get the output to total up the line and get everything but the * sign between the numbers. Hoping that someone out there can lend a helping hand. Here is the code that I have completed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>Assignment 1</title>
    <script>
        var num = "";
        var match ="";


var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";

for(var i=1; i<=size; i++)
{
    if (i < size){
  num = num  +  i + " " 

  } if (i==size) {
  num =num + i }


   total= total * i;
  document.write(num   + " = "+ total + "<br>"); 
}
 }else {
 alert("Please enter a number equal to or greater than 1");
 }
var total="1";
    </script>
</head>
<body>
    <main>
        <!-- Will show after the script has run -->
        <h1>Assignment 1</h1>
    </main>
</body>
</html>

-

I am looking for output like this

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

and so on. Thanks again

3
  • prompt returns a string or null. you should be converting the result to a number first. Commented Oct 16, 2018 at 17:36
  • 1
    So what is wrong with what you got? Why is there var total="1"; after the loop? I do not see you adding a * when you are building your string. Commented Oct 16, 2018 at 17:38
  • 2
    Please use proper (and consistent) indentation. This will make your (and our) life easier ;) Commented Oct 16, 2018 at 17:40

1 Answer 1

1

You can use a loop like this and make the total time the new iteration value:

var total = 1;
var newList = [];
for(let i=1; i<=5; i++) {
  newList.push(i);
  total *= i;
  console.log(newList.join('*') + '=' + total)
}

Run code snippet output:

1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
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.