When to break?
The order in which you execute your code inside the loop and check when you should break is important. The following would run the code
a different number of times.
# Code, then check condition
repeat {
code
if(condition) {
break
}
}
# Check condition, then code
repeat {
if(condition) {
break
}
code
}
Let's see this in an extension of the previous exercise. For the purposes of this example, the runif()
function has been replaced with a static multiplier to remove randomness.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- The structure of a
repeat
loop has been created. Fill in the blanks so that the loop checks if thestock_price
is below66
, andbreak
s if so. Run this, and note the number of times that the stock price was printed. - Move the statement
print(stock_price)
to after the if statement, but still inside the repeat loop. Run the script again, how many times was thestock_price
printed now?
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Stock price
stock_price <- 67.55
___ {
# New stock price
stock_price <- stock_price * .995
print(stock_price)
# Check
if(stock_price ___ ___) {
print("Stock price is below 66! Buy it while it's cheap!")
___
}
}