While loops: Final video for lecture 9, covers while loops. Recall for loops from last in person lecture. Run for a specified number of iterations, which is equal to the length of the vector going over. For loop syntax (display each value from 1 to 10): for i=1:10 disp(i) end Unlike for loops, while loops will run so long as a boolean expression is true. First saw a while loop in homework 3, where the user was repeatedly prompted until the quit option was chosen. While loop syntax: while boolean_expression statements to execute if boolean_expression is true end If statements: check boolean expression once and execute statements at most once While loops: check boolean expression at every iteration and execute statements every time it is true Basic execution of a while loop (high level): 1. The boolean expression is evaluated to true or false. 2. If the boolean is true, then execute the statements in the body of the while loop. 3. After executing the statements in the body, go back to the top of the while loop 4. The boolean expression is reevaluated. 5. If the boolean evaluates to true, the body of the while loop is executed, and the boolean is evaluated again. 6. This process repeats until the boolean expression evaluates to false. 7. If the boolean evaluates to false, the statements in the body of the while loop are skipped and control continues at the next statement after the while loop. While loop example: Roll a die until 3 10's have been seen and display the number of rolls required to see 3 10's. Warning: If the boolean expression will always evaluate to true, will get an "infinite loop" Show simple example (x = 0; while x >= 0 x = x + 1; end) Use ctrl+C to break out of an infinite loop in MATLAB (stops execution of code) for vs while vs if Body of for executes once for each item in its control vector Body of while exectues repeatedly while its boolean expression is true Body of if executes once if its conditional expression is true