## What is a While loop?

**if statement.**

The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within the block is executed. This repeats until the condition/expression becomes false. Because the while loop checks the condition/expression before the block is executed, the control structure is often also known as a

**pre-test loop.**

What they do is simply do a test like an if-statement, but instead of running the code block once, they jump back to the "top" where the while is, and repeat. A while-loop runs until the expression is False.

## What does the while loop do?

**For example,**say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. If we know a specific number, such as 32, we can say 5 times, but for a given symbolic variable "NUMBER" which represents any number in the world, how many times is not known a priori (before hand). In this case, we could use a while loop to determine that answer:

The "pseudocode" for such an algorithm is: while the number is bigger than one keep dividing it by two. additionally, keep a count of how many times we do the division.

Therefore, the while loop;

- Like all loops, "while loops" execute blocks of code over and over again.
- The advantage to a while loop is that it will go (repeat) as often as necessary to accomplish its goal.

## Worked example

**Here is a mathlab example that can find the factorials of 10. This means 10x9x8x7x6x5x4x3x2x1**n = 10;

f = n;

while n > 1

n = n-1;

f = f*n;

end

disp(['n! = ' num2str(f)])

**Solution**

n! = 3628800

**Pseudocode**

Let n be 10

f is equal to n

while n is greater than 1

the new value of n is the old value of n less 1

new value of f is a product of the old value of f and the new value of n

endwhile

print factorial

**Flowchart Extract**