The do…while Loop
C’s third loop construct is the do…while loop, which executes a block of statements as long as a specified condition is true. The do…while loop tests the condition at the end of the loop rather than at the beginning, as is done by the for loop and the while loop.The structure of the do…while loop is as follows:
Structure do while loop
The statements associated with a do…while loop are always executed at least once. This is because the test condition is evaluated at the end, instead of the beginning, of the loop. In contrast, for loops and while loops evaluate the test condition at the start of the loop, so the associated statements are not executed at all if the test condition is initially false.
do while loop syntex in C
condition is any C expression, and statement is a single or compound C statement. When program execution reaches a do…while statement, the following events occur:
//syntex do while loop
do{
statements;
}while (condition);
Example 1
/* prints even though condition fails! */
int x = 10;
do {
printf(“\nThe value of x is %d”, x );
}while (x != 10);
Example 2
/* gets numbers until the number is greater than 99 */
int nbr;
do {
scanf(“%d”, &nbr );
}while (nbr <= 99);
Example 3
/* Enables user to enter up to 10 integer values*/
/* Values are stored in an array named value. If 99 is */
/* entered, the loop stops*/
int value[10];
int ctr = 0;
int nbr;
do {
puts(“Enter a number, 99 to quit “);
scanf( “%d”, &nbr); value[ctr] = nbr;
ctr++;
}while (ctr < 10 && nbr != 99);
What is a Do While loop in C?
Advertisements. Unlike for and while loops, which test the loop condition at the top of the loop, the do…while loop in C programming checks its condition at the bottom of the loop.
Why do while loop is used?
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.
What is a loop statement?
In looping, a program executes the sequence of statements many times until the stated condition becomes false. … The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false