Get startedGet started for free

While with a print

While loops are slightly different from repeat loops. Like if statements, you specify the condition for them to run at the very beginning. There is no need for a break statement because the condition is checked at each iteration.

while (condition) {
    code
}

It might seem like the while loop is doing the exact same thing as the repeat loop, just with less code. In our cases, this is true. So, why ever use the repeat loop? Occasionally, there are cases when using a repeat loop to run forever is desired. If you are interested, click here and check out Intentional Looping.

For the exercise, imagine that you have a debt of $5000 that you need to pay back. Each month, you pay off $500 dollars, until you've paid everything off. You will use a loop to model the process of paying off the debt each month, where each iteration you decrease your total debt and print out the new total!

The variable debt has been created for you.

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

  • Fill in the while loop condition to check if debt is greater than 0. If this is true, decrease debt by 500.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Initial debt
debt <- 5000

# While loop to pay off your debt
while (debt > ___) {
  debt <- debt - ___
  print(paste("Debt remaining", debt))
}
Edit and Run Code