0

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

2
  • i+num2 -> i += num2 Commented Aug 3, 2020 at 4:43
  • Also, the console.log(i) needs to be inside the loop. Commented Aug 3, 2020 at 4:44

4 Answers 4

1

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

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

Comments

0

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)

1 Comment

this is great, i have been having a problem with functions but this is very clear
0

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

Comments

0

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

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.