LoslegenKostenlos loslegen

Break it

Sometimes, you have to end your while loop early. With the debt example, if you don't have enough cash to pay off all of your debt, you won't be able to continuing paying it down. In this exercise, you will add an if statement and a break to let you know if you run out of money!

while (condition) {
    code
    if (breaking_condition) {
        break
    }
}

The while loop will completely stop, and all lines after it will be run, if the breaking_condition is met. In this case, that condition will be running out of cash!

debt and cash have been defined for you.

Diese Übung ist Teil des Kurses

Intermediate R for Finance

Kurs anzeigen

Anleitung zur Übung

  • First, fill in the while loop, but don't touch the commented if statement. It should decrement cash and debt by 500 each time. Run this. What happens to cash when you reach 0 debt?
  • Negative cash? That's not good! Remove the comments and fill in the if statement. It should break if you run out of cash. Specifically, if cash equals 0. Run the entire program again.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

# debt and cash
debt <- 5000
cash <- 4000

# Pay off your debt...if you can!
while (debt ___ 0) {
  debt <- debt - ___
  cash <- cash - ___
  print(paste("Debt remaining:", debt, "and Cash remaining:", cash))

  # if (___ == ___) {
  #   print("You ran out of cash!")
  #   ___
  # }
}
Code bearbeiten und ausführen