ComeçarComece de graça

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.

Este exercício faz parte do curso

Intermediate R for Finance

Ver curso

Instruções do exercício

  • 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?

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

# 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!")
    ___
  }

}
Editar e executar o código