Hi, first time posting. I came across this code on one of the practices on the app.

The answer is 23 but I can’t figure out how the code got to this number. Could someone please explain it to me or give me a hint? Thanks.

Hi, first time posting. I came across this code on one of the practices on the app.

The answer is 23 but I can’t figure out how the code got to this number. Could someone please explain it to me or give me a hint? Thanks.

const values = [1, 10, 4, 3, 15, 3, 5, 2];
let total = 100
for (let i = values.length -2; i>= 0; i-=2) {
let a = values[i];
total /= a;
total += 10;
}
console.log(total)
//23

Hi,

So, the loop is set up to start with i equal to the length of values (which is 8) minus 2. I.e. 6.

It’ll run until i is no longer 0 or above, and each loop will take 2 from i (so it’ll go 6, 4, 2, 0, then stop because the next would be -2.

within the loop a takes the value of values at index i - so for the first loop, index 6 would be 5.

total then becomes the result of dividing itself by a. So, it’s new value is 100 / 5 = 20.

Then it adds 10 to it to make 30 and the loop begins again.

That’s the first loop. Hopefully it’s clear enough to go from there.

Ok, I got it, thanks!

My problem was that I was adding the total after the loop had finished entirely, rather than after every loop.

Thanks again!

1 Like