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.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- First, fill in the while loop, but don't touch the commented if statement. It should decrement
cash
anddebt
by500
each time. Run this. What happens tocash
when you reach0
debt
? - Negative cash? That's not good! Remove the comments and fill in the if statement. It should
break
if you run out ofcash
. Specifically, ifcash
equals0
. Run the entire program again.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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!")
# ___
# }
}