Loop question break down

Hi everyone! I wonder if anyone would be willing to break down the answer to this question:

What is the value that is computed by this code block?
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;

I actually got it right, so I know the answer is ‘23’ and their explanation is ’ The loop variable (i is 6, 4, 2, 0) accesses the values in the order: 5, 15, 4, 1.’ if anyone would be willing to explain this step by step I would greatly appreciate it!

Hi there, and welcome to the forums!

Essentially what this is doing is taking every second element starting from the end, dividing the total by that and adding 10. I will break down a couple of the passes but not the entire process as due to the nature of it being a loop, it’s much the same every pass.

  1. values and total variables are declared and initialised.
  2. The loop conditions are initialised. In this case, i takes the starting value of 8-2 = 6. Then over the course of the loop i will decrease by 2 until no longer bigger than or equal to 0. This just ensures that no invalid indexes are read.
  3. a is initialised to be the value of values[i]. As we said i is initialised to 6, therefore a = values[6], which is equal to 5 since arrays are 0-indexed in JS.
  4. total is set equal to it’s current value divided by this a value. Therefore total = 100/5 = 20.
  5. 10 is then added to total, giving total a final value of 30 on first pass.
  6. The process then repeats, with i becoming this time 6-2 = 4. This means that a = values[4] = 15. Then total = 30/15 = 2. And finally on this pass total = 2 + 10 = 12. The process then repeats until the final stage is reached and an answer is finalised.

Hopefully that break down makes sense and helps, let me know if you have any further questions!

Thank you, Adam! That was very helpful. I think what threw me off was that there was a single numerical answer. Your explanation cleared up a few uncertainties for me. I appreciate your energy in helping me think through this question.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.