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.
Questo esercizio fa parte del corso
Intermediate R for Finance
Istruzioni dell'esercizio
- 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?
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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!")
___
}
}