#Understanding how to change a for loop into a while loop

13 messages · Page 1 of 1 (latest)

wanton stratus
#

I understand most of what's been asked of me when it comes to loops, but I'm having a bit of problem understanding how to convert a for loop into a while loop

This is the code I did in a forloop

const population = [67330000, 2828000, 67750000, 47420000];
const percentages2 = [];

for (let j = 0; j < population.length; j++) {
percentages2.push((population[j] / 7900) * 100);
}
console.log(percentages2);

Basically I'm doing an assignment as part of the course I'm currently doing, but I just don't know how to do the same code in a while loop... I'm unsure if how I've done is correct, but I'll include it down below either way.. I feel as if my code here is falling into the DRY bracket...

let population = [67330000, 2828000, 67750000, 47420000];
let percentages3 = []

while (percentages3.length !== population.length) {
percentages3.push((population[0] / 7900) * 100);
percentages3.push((population[1] / 7900) * 100);
percentages3.push((population[2] / 7900) * 100);
percentages3.push((population[3] / 7900) * 100);
}

console.log(percentages3);

I appreciate anyone who can help me out 🙂

wanton stratus
#

Thanks in advance Bill 🙂 I can see your typing

obsidian lotus
#

Bill is always getting the questions before everyone. 😄

#

This worked for me while trying to refactor your code: while(percentages3.length < population.length) { percentages3.push((population[percentages3.length] / 7900) * 100); }

rapid harness
#

Conceptually all loops continuously repeat based on some condition.

A for loop is so common that there's a special structure to it - but basically you're doing a couple of things:

  1. Setting the initial value of some variable
  2. Checking the value of the variable against some number
  3. Incrementing the variable

So to do that with a while loop:

let j = 0; // init the variable
while(j < percentages3.lengh) { // check the condition
  ...
  j++; // increment the condition
}

There you have it!

wanton stratus
#

Thanks you guys! You've managed to make it so much clearer in my head now!!!

rapid harness
#

My answer was a little generic about how to convert a for to a while "generically", @obsidian lotus 's answer is the exact answer to your situation... glad if this is of some help

wanton stratus
#

Yeah Bill your answer was fine too! I do know that there's always 3 values with for loops, but I didn't realise that this was true to while loops true

#

I've been doing so much studying man hahahaha

#

I'm loving the journey to be honest, and to be fair that's like the 2nd time I've been stuck on something throughout the whole of the fundamentals part of my course

#

I've got 1 more challenge to go and then its on to learning about the DOM!

#

But thanks you guys I really do appreciate your help ❤️

rapid harness