Run a loop n times

I'm writing a program that will calculate a number entered by the user multiplied by 2.

I realised I need a for loop so that the Value will increment by 1 and multiple by 2

The problem is I want to know how to run this loop only 10 times - at the current moment it will run for ever and I had to place an if statement to break out of the loop if the value reaches 50.

//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (value;; value++) {
  value2 = value * 2;
  document.write(`${value} multiply 2 -> ${value2}`);
  document.write('<br>');
  //i placed this if statement to break out of the for loop as it //will run forever
  if (value > 50) {
    break;
  }
}

Answers:

Answer

you can use a counter variable to keep a check on number of iterations. I am guessing you want to increase value by 1 after each iteration. You can do something like this:

  //prompt user to enter number
    let value = prompt("Enter A number");
 //user entered number will loop through while output will show multiples //of 2
    for (var i=1;i<=10; i++) {
      value2 = value * 2;
      document.write(`${value} multiply 2 -> ${value2}`);
      document.write('<br>');
      //i placed this if statement to break out of the for loop as it //will run forever
      value++;

    }
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <!--
<script type="text/javascript" src="js.js"></script>
-->
</head>

<body></body>

</html>

Answer
<!DOCTYPE html>
<html>
<body>

<h2>Multiple By 2</h2>

<input type="text" id="num"/>

<button onclick="multiply()">multiply by 2</button>

<script>
function multiply() {
    var number = document.getElementById("num").value;
    for(i=1;i<11;i++){
       console.log(number*i);

    }  
}

</script>

</body>
</html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.