While loop

We have seen that for loops can repeatedly execute a block of code for each element specified. We can think of another scenario where we only want to continue executing a block of code as long as a given condition is TRUE. The basic idea is:

    WHILE there is money in my account
        have lunch out
        update my bank statement

In while loops the condition is checked at the beginning of each iteration and the loop continues executing as long as the condition is TRUE. The basic syntax in R which has a similar scaffolding to an if clause:

while (condition) {
    # code to execute while condition is True
}

To ensure that the condition will eventually become FALSE, it is common usage to increment/decrement a counter variable in the loop body:

count <- 0
while ( count < 5 ) {
    cat(count, " ")
    count <- count + 1
}
0  1  2  3  4  

There are some extra flow control instructions in while loops that we are not going to see here in detail but it is important to mention them. They are:

while (TRUE) {
    user_input <- readline("Enter 'q' to quit: ")
    if (user_input == 'q') {
        break
    }
}
Exercise

Given a list of students sorted by name

students <- c("Alice", "Bob", "Charlie", "Frank", "George", "Hannah", "Julia", "Mia", "Noah", "Olivia")

create a script while.R that prints the names of students starting with letters before ‘M’ in the alphabet.

Note in the below script that the while loop needs to take into account two different conditions:

  • That the student’s name starts with a letter before ‘M’
  • That we don’t try to index an element out of range in students
students <- c("Alice", "Bob", "Charlie", "Frank", "George", "Hannah", "Julia", "Mia", "Noah", "Olivia")

# Initialize the index
i <- 1

# While loop to print names before 'M'
while (i<length(students) & students[i]<"M") {
    cat(students[i], " ")
    i <- i + 1
}
Alice  Bob  Charlie  Frank  George  Hannah  Julia