Comp 110 While Loops

The Structure of a While Loop

while (<boolean expression "test">) {

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

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

}

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

What do you need?

  1. A boolean condition
    1. located in the () of the while statement
    2. can use any boolean operator (===, !==, >, <, >=, <=)
    3. can also use a boolean variable (aCondition === false, !aCondition)
  2. Code inside the while { } that does something useful
    1. can be used to iterate through items in an array and more!
  3. A 'counter' variable or variable that will eventually change to make the boolean condition false and end the loop

Examples of counters:

Numerical counter: 

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

Boolean expression:

while(uncIsWinning){
     //looping code
     if(uncScore<opponentScore){
          uncIsWinning = false;
     }
}

Why is my loop not working?

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++; 
     // 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 is equal to 109), the while loop will end and "Done" will be printed