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
.
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.
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.
Write a program that asks the user to enter a grade until the grade is not between 0 and 20.
float grade;
// Entering the grade between 0 and 20
// COMPLETE HERE
// Display the grade
printf ("The grade is %.1f.\n", grade);
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
The grade is 16.4.
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
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
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?
while(1);
) or wait for an external event with a loop.
Try again...
What are the valid loops in C?
What does the following code display?
int x=7;
do {
printf ("%d ", ++x);
} while (x<10);
x
is 9 before increment.
Try again...
What does the following code display?
int x=7;
do {
printf ("%d ", x--);
} while (x>=5);
x
is 5 before the printf
.
Try again...
What does the following code display?
int x=2;
do {
x=x+1;
} while (x<=10);
printf ("%d", x);
x
is less or equal to 10, we go on. So we exit the loop at 11.
Try again...
What must the user enter to exit the loop?
int x;
do{
scanf ("%d", &x);
} while (x<0 || x>100);
x
is less than 0 or greater than 100, we loop.
Try again...
What must the user enter to exit the loop?
int x;
do{
scanf ("%d", &x);
} while (x<0 && x>100);