Write a while loop
Let's get you started with building a while loop from the ground up. Have another look at its recipe:
while (condition) {
expr
}
Remember that the condition part of this recipe should become FALSE at some point during the execution. Otherwise, the while loop will go on indefinitely.
If your session expires when you run your code, check the body of your while loop carefully.
Have a look at the sample code provided; it initializes the speed variables and already provides a while loop template to get you started.
This exercise is part of the course
Intermediate R
Exercise instructions
Code a while loop with the following characteristics:
- The condition of the
whileloop should check ifspeedis higher than 30. - Inside the body of the
whileloop, print out"Slow down!". - Inside the body of the
whileloop, decrease thespeedby 7 units and assign this new value tospeedagain. This step is crucial; otherwise yourwhileloop will never stop and your session will expire.
If your session expires when you run your code, check the body of your while loop carefully: it's likely that you made a mistake.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Initialize the speed variable
speed <- 64
# Code the while loop
while (___) {
print("___")
speed <- ___
}
# Print out the speed variable
speed