# Lesson 6.1. do..while loop in C

In C, it is possible to automatically repeat blocks of instructions until a condition is true (or false). This type of repetition is called a loop. In C, there are 3 loops:

In this chapter, we will study each of these loops starting with the do..while.

## Syntax

The do..while loop repeats a block of instructions while the condition is true :

do {
// ...
Instructions block
// ...
}
while (test);

Here is the flowchart for the do..while loop:

The instruction block is also called the body of the loop. It is the part between the curly braces. One execution of the loop is called an iteration.

With the do..while loop, the body of the loop is necessarily executed once, even if the test is false at the first iteration.

With the do..while loop, the body of the loop is required to be executed at least once, even if the test is false on the first iteration.

## Example

Here is an example of a do..while loop that asks the user to enter a number as long as it is not strictly negative.

int n;
do {
// Body of the loop: ask a number to the user
printf ("Enter a negative integer: ");
scanf ("%d", &n);
}
while (n>=0);
printf ("You entered %d.\n", n);

The loop will be repeated while n is positive or zero.

## Exercise 1

Write a program that asks the user to enter a grade until the grade is not between 0 and 20.

// Entering the grade between 0 and 20
// COMPLETE HERE

Here is the expected output:

Enter the grade between 0 and 20: -5
Enter the grade between 0 and 20: 22
Enter the grade between 0 and 20: 16.4

## Exercise 2

Write a program with a do..while loop that counts from 3 to 22 according to the following pattern:

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

## Exercise 3

With a do..while loop, display the following sequence:

\$\$ U_{n+1} = U_{n} * 2 \$\$

with \( U_0 = 1 \)

Display the sequence until (U_n\) is less than or equal to 1024 according to the following model:

1 2 4 8 16 32 64 128 256 512 1024

## Quiz

For the analysis of the programs below, it is best to have a paper and pencil.

In programming, what can a loop be used for?

What are the valid loops in C?

What does the following code display?

int x=7;
do {
printf ("%d ", ++x);
} while (x<10);

What does the following code display?

int x=7;
do {
printf ("%d ", x--);
} while (x>=5);

What does the following code display?

int x=2;
do {
x=x+1;
} while (x<=10);
printf ("%d", x);

What must the user enter to exit the loop?

int x;
do{
scanf ("%d", &x);
} while (x<0 || x>100);

What must the user enter to exit the loop?

int x;
do{
scanf ("%d", &x);
} while (x<0 && x>100);