Do While Looping Presentation (2) (Read-Only)
Do While Looping Presentation (2) (Read-Only)
WHILE
LOOPING
PRESENTATION BY:
DULULA H240209R
DZIMANO H240108Y
GAMBIZA H240701Y
GARAPO H240337N
HWENGWERE H240320E
DO..WHILE LOOPING
A do while loop is a control flow statement that executes a block of code at least once,
and then repeatedly executes the block, or not, depending on a given Boolean condition
at the end of the block.
•OR
do {
// Code to be
executed}
while (condition);
Example (1):
#include <stdio.h>
int main(void)
{
int i=0;
do
{
printf("i: %d\n", i);
i++;
}while (i<5);
printf("loop completed!\n");
return 0;
}
EXAMPLE 2
#include <stdio.h>
int main ()
{
int i =1;
do
{
printf(“%d\n”,i);
i++;
}
while (i<=5);
return 0;
}
KEY POINTS
The do-while loop is guaranteed to execute its code block at least
once ,unlike the while loop ,which might not execute at all if the
condition is initially false .
The condition is checked after the code block is executed .
In the example ,the loop will print the numbers 1 to 5.
How it works:
1. The code block inside the do statement is
executed.
2. The condition in the while statement is
evaluated.
3. If the condition is true, the code block is
executed again, and the process repeats from
step 2.
4. If the condition is false, the loop terminates
Use Cases:
o When you need to execute a block of code at
least once before checking a condition.
o For tasks like displaying a menu and allowing
the user to make a choice, where the menu
should always be shown at least once.
o When you need to ensure that a certain
operation is performed at least once,
regardless of the initial condition.
The difference between while command and do while
command is: