ComenzarEmpieza gratis

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.

Este ejercicio forma parte del curso

Intermediate R for Finance

Ver curso

Instrucciones del ejercicio

  • 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.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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!")
  #   ___
  # }
}
Editar y ejecutar código