Comp 110 While Loops

What is a While Loop?

A while loop is a block of code that will continue 'looping' (repeating) until its boolean condition becomes false. See the correct example below.

Structure

while (<boolean expression "test">) {

     // useful code that executes as long as the boolean expression is true

     // manipulation of 'counter' variable i.e. i++
     // or boolean condition i.e. if(<x>) { boolean = false;}

}

While Loop Checklist

  1. Boolean condition
    1. Located inside the () of the while statement
    2. Can use any boolean operator (===, !==, >, <, >=, <=)
    3. Can also use a boolean variable (aCondition, !aCondition)
  2. Code inside the while { } that does something useful
  3. A 'counter' variable or a variable that will eventually change to make the boolean condition false and end the loop -- should be placed inside the body of the while loop

Examples of Counters

Numerical counter:

while (i<10) {
     // looping code
     i++;
}

Boolean expression:

while (sprinklesIsAlive) {
     // looping code
     if (dwightsCare < adequateCare) {
          sprinklesIsAlive = false;
     }
}

My Loop Killed Chrome!

Is it an infinite loop? Make sure that your condition can eventually become false! Example:

// incorrect:
let i: number = 0;
while (i < 110) {
     print("I love COMP110");
}
print("Done");
// the number 'i' is never changed and thus will never be >= to 110, therefore the while loop will INFINITELY execute and the string "Done" will never print.

// correct:
let i: number = 0;
while (i < 110) {
     print("I love COMP110");
     i++; 
     // i++ is equivalent to i = i + 1;
}
print("Done");
// i increments up by 1 each time the loop executes
// when the code has executed 110 times (or when i is equal to 109), the while loop will end and "Done" will be printed

Nested Loops!

We can nest while loops -- meaning we can place one while loop inside of another! Looking at an example might clear this up a little:

export let oldMacdonald = (): string => {
    let sound = "";
    let i = 1;
    while (i < 20) {
        let count = 0; // each time the outer loop runs count will restart at 0
        while (count < 4) {
            i *= 2; // increase the value in i, the counter variable for the outer loop 
            count++; // increment count, the counter variable for the inner loop
            sound += "e";
        }
        sound += "-iii-";
    }
    sound += "oh";
    return sound;
};
print(oldMacdonald()); // prints the string "eeee-iii-eeee-iii-oh"

The oldMacdonald function uses nested loops to build up a string. The inner loop starts over and runs through again each time we reenter the outer loop.

After the function definition, we call this function within a print statement, so the returned result of the function call gets printed out.