# Do while loop

The do while loop is a post-condition loop. It guarantees to execute its body at least once, regardless of the loop condition. The reason for this is that in a post-condition loop the condition is checked after the body of the loop. ## The do while loop in C

The syntax of the do while loop in C is:

do
{
...
Statements in the loop body
...
}while(condition);

• do is the keyword that starts the loop.
• Next follows the body of the loop. It is allowed to omit the curly brackets if the body contains only one statement, but this is a bad coding practice and you should avoid it.
• The last part is the condition - while();

For beginners it is a common mistake to forget the semicolon after the condition.

The loop will repeat the execution of the body while the condition is true. Once it becomes false, no more iterations are done and the program continues with the next statement, following the loop.

## Examples

### Calculating n! (n factorial)

Factorial is the product of all integer numbers from 1 to n, where n is the factorial we want to calculate. In mathematics it is written with an exclamation mark – n!
So..  4! = 1*2*3*4 = 24

Here is the code to calculate 5! using a do while loop:

```#include <stdio.h>
int main()
{
int factorial = 1;
int number = 5;
do
{
factorial *= number;
number--;
}while(number > 0);
printf("%d\n", factorial);
}
```

Another common example is a menu. We can print a menu and take different actions, depending on the user input. Here is a typical implementation:

```int main()
{
do
{

return 0;
}

{
printf("Input a number to take action:\n");
printf("1. Input a number to calculate its factorial\n");
printf("0. Exit\n");
}

{
int number;
unsigned long factorial;
{
printf("number = ");
scanf("%d", &number);
factorial = calculateFactorial(number);
printf("%d! = %lu \n", number, factorial);
}
}
```

The demo shows a menu and calculates n!
Here is how it works: In this example I wanted to keep the code short. For that reason you see only 2 options in the menu. Also, normally you will handle the user choice with a switch, rather than an if.

Now you can implement the functions printMenu() and handleMenuChoice() the way you like. For instance you can ask the user to input a sequence of numbers and find the greatest of them.