简体   繁体   中英

how can i use a for loop to count to and count by a number in javascript?

Create a program that takes two numbers - one to count to and another to determine what multiple to use to get there.

Here is some sample input:

Count to: 30 Count by: 5 Output: 5, 10, 15, 20, 25, 30

Count to: 50 Count by: 7 Output: 7, 14, 21, 28, 35, 42, 49

here is my trial code.

 var num1 = parseInt(prompt("Count to: ")); var num2 = parseInt(prompt("Count by: ")); for(let i = num2; i <= num1; i+num2){ } console.log(i);

You need to increase the value of i in your loop as i+num does not increase its value:

 // Changed the variable names to something more descriptive // to avoid confusion on larger code bases; var maxValue = parseInt(prompt("Count to: ")); var stepValue = parseInt(prompt("Count by: ")); // Can also be written as index += stepValue for(let index = stepValue; index <= maxValue; index = index + stepValue) { // Print the current value of index console.log(index); }

Use modulus operator in your loop with a conditional that checks if the modulus of the number iterated is equal to zero...

Count to: 30 Count by: 5 Output: 5, 10, 15, 20, 25, 30

 let targetNumber = 30; for(let i = 1; i <= targetNumber; i++){ if( i % 5 === 0){ console.log(i) } }

Count to: 50 Count by: 7 Output: 7, 14, 21, 28, 35, 42, 49

 let targetNumber = 50; for(let i = 1; i <= targetNumber; i++){ if( i % 7 === 0){ console.log(i) } }

Below snippet could help you

 function count(countTo, countBy) { const arr = [] for (let i = countBy; i <= countTo; i += countBy) { arr.push(i) } console.log(arr.join(', ')) } count(30, 5) count(50, 7)

Your setup was good, only the console.log statement needs to be inside the loop to print.

var num1 = parseInt(prompt("Count to: "));
var num2 = parseInt(prompt("Count by: "));
for (let i = num2; i <= num1; i += num2) {
  console.log(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM