This lesson will show you how to:
- Use the while loop
- Use the do-while loop
Loops -- While:
We have already encountered the While and for loops. In
While ( expression )
statements
while
The while loop is used to execute a block of code as long as some condition is true. If the condition is false from the start the block of code is not executed at al. The while loop tests the condition before it's executed so sometimes the loop may never be executed if initially the condition is not met. Its syntax is as follows.
while (tested condition is satisfied)
{
block of code
}
While Example
x = 0;
while (x < 3)
{
x++;
}
Example program:
/* Sample program including the while loop */
#include
int main(void)
{
int loop = 0;
while (loop <=10)
{
printf(“%d”, loop);
++loop
}
return 0;
}
Sample program output
0
1
…
10
Do While:
The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while.
"do ....while" loops syntax is as follows
do
{
block of code
} while (condition is satisfied);
The do while statement
The do {} while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed at least once
/* Demonstration of the do…..while loop */
#include
int main(void)
{
int value, r_digit;
printf(“Enter a number to be reversed.\n”);
scanf(“%d”, &value);
do
{
r_digit = value % 10;
printf(“%d”, r_digit);
value = value / 10;
} while (value != 0);
printf(“\n”);
return 0;
}