Exercise

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.

Instructions

100 XP
  • The structure of a repeat loop has been created. Fill in the blanks so that the loop checks if the stock_price is below 66, and breaks 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 the stock_price printed now?