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.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- The structure of a
repeatloop has been created. Fill in the blanks so that the loop checks if thestock_priceis below66, andbreaks 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_priceprinted now?
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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!")
___
}
}