CarlosP
CarlosP

Reputation: 11

Loop is not incrementing

I am new to javascript.

I have to create a function that returns the next multiples of 5 based on a given number.But my loop repeats the information, it doesn´t increment the result.What am I doing wrong?

function proS(num, mult) {
  let arr = []

  for (var i = 1; i <= mult; i++) {
    arr.push(Math.ceil(num / 5) * 5)
  }
  return arr
}

proS(6, 4)

returns [10, 10, 10, 10]

Upvotes: 0

Views: 327

Answers (5)

CarlosP
CarlosP

Reputation: 11

thanks guys, I ended up doing this and it worked:

function proS (num, mult){
let arr = []
let res = (Math.ceil(num / 5) * 5)

for (var i = 1; i <= mult; i ++){
arr.push(res)
res += 5
}
return arr
}

Upvotes: 1

Jonathan Mardones
Jonathan Mardones

Reputation: 1

The loop is returning and pushing to the array the same value every round because the expression you have inside the loop is invariant for i changes. With the expression Math.ceil(num / 5) * 5 you're getting the next multiple of 5 of the num parameter. You have to increase this number by 5 every on every loop iteration. For example, try this:

function proS (num, mult){
    let arr = []
    const nextMultipleOf5 = Math.ceil(num / 5) * 5
    for (var i = 0; i <= mult - 1; i ++){
        arr.push(nextMultipleOf5 + 5*i)
    }

    return arr
}

Upvotes: -1

BetzMan
BetzMan

Reputation: 1

You are pushing the same value to the array without changing it at any point.

Math.ceil(num / 5) * 5 

does not change because num does not change

for (var i = 0; i < mult; i ++){
   arr.push((Math.ceil(num / 5)+i) * 5)
}

will increment each result by 5 according to i

Upvotes: -1

Barmar
Barmar

Reputation: 781058

you should use your formula to produce the initial value of num, then add 5 to it each time through the loop.

function proS(num, mult) {
  let arr = []
  num = Math.ceil(num / 5) * 5;
  for (var i = 1; i <= mult; i++, num += 5) {
    arr.push(num)
  }
  return arr
}

console.log(proS(6, 4))

Upvotes: 4

Tom&#225;s Rivera H.
Tom&#225;s Rivera H.

Reputation: 66

I won't write the answer, but I'll point you in the right direction. If you pay close attention arr.push(Math.ceil(num / 5) * 5) this bit of code is invariant. This means that you should probably add the variable i somewhere in there so that it actually returns a different output every iteration of the loop.

Upvotes: 1

Related Questions