11.3. Loop control#

Sometimes it may be necessary to interrupt the normal flow of a loop to either terminate the the loop before the loop has been completed or to move to the next iteration straight away. To do this MATLAB uses the break and continue commands.


11.3.1. Break#

The break command is used to exit a loop straight away without executing any more commands within the loop. To demonstrate the use of a break command enter the following code into your program.

fprintf(“\n”)

for i = 1 : 5 if i == 4 break end

fprintf("%1i\n", i)

end


Run your program and you should see the following printed to the console

```text
1
2
3

Here the if statement inside the for loop terminates the loop then i is equal to 4.


11.3.2. Continue#

The continue command moves onto the next cycle of a loop straight away without executing any following commands in the loop. To demonstrate the use of a continue command enter the following code into your program.

% The continue command
fprintf("\n")

for i = 1 : 5
    if i == 4
        continue
    end

    fprintf("%1i\n", i)
end

Run your program and you should see the following printed to the console

1
2
3
5

Here the if statement inside the for loop skips the iteration when i is equal to 4 and continues to the next iteration.


11.3.3. Exercises#

Exercise 11.6

A prime number is a positive integer greater than 1 which is only divisible by 1 and itself. Write a program that uses a for loop to determine whether an integer is prime or not. Use your program to determine of the following are prime:

  1. 1009 (prime)

  2. 2123 (not prime)

  3. 6269 (prime)

  4. 8441 (not prime)

Hint: The command mod(n, i) returns 0 if n is divisible by i.

Exercise 11.7

Use a while loop to create a guessing game where the user has to guess the value of a random integer between 0 and 100. For each guess the game will tell the user whether their guess is greater or less than the random integer. The user wins the game if they guess correctly within 5 guesses.

Hints:

  • the command a = input(text) can be used to prompt the user to enter a number and store the result in the variable a

  • the command randi(a) generates a random integer in the range 1 to a