# Loops

## While

While loops are used to repeatedly execute a statement as long as the underlying expression stays true.

They follow the format:

define variable;

while (expression)

statement;

increment;

end

Here we are using the following code:

x = 1;

while (x <= 5)

fprintf('The value of x is %i\n', x);

x = x + 1;

end

This gives a result in the command window of:

The value of x is 1

The value of x is 2

The value of x is 3

The value of x is 4

The value of x is 5

N.B. The %i means that the number should be an integer and \n signifies a linebreak. On the otherhand, the , x determines which variable this applies to. This is not specific to the while loop and is not needed for mathematical operations.

## For

For loops are used execute a statement for a set number of times. As such, unlike the while loop, the variable should not be pre-defined and no increment is needed

They follow the format:

for (variable = [lower limit:increment:upper limit])

statement;

end

Here we are using the following code:

for (x = [1:1:5])

fprintf('The value of x is %i\n', x);

end

This gives a result in the command window of:

The value of x is 1

The value of x is 2

The value of x is 3

The value of x is 4

The value of x is 5

## Nested

Nested loops are just a combination of multiple loops contained within one another.

They do not follow a particular format since they can come in various forms. As such the following code is only an example of a nested loop which also uses the 'if function' designed to print all prime numbers between 1 and 20:

for (x = [2:1:20])

for (y = [2:1:20])

if (~mod(x,y))

break

end

end

if (y > (x/y))

fprintf('%i is a prime number\n', x);

end

end

This gives a result in the command window of:

2 is a prime number

3 is a prime number

5 is a prime number

7 is a prime number

11 is a prime number

13 is a prime number

17 is a prime number

19 is a prime number