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.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- First, fill in the while loop, but don't touch the commented if statement. It should decrement
cashanddebtby500each time. Run this. What happens tocashwhen you reach0debt? - Negative cash? That's not good! Remove the comments and fill in the if statement. It should
breakif you run out ofcash. Specifically, ifcashequals0. Run the entire program again.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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!")
# ___
# }
}