C Programming Tutorial
Computer Tutorial

The do- While Loop



The do- While Loop

The do-while loop behavior is virtually the same as the while loop except that it always executes the statement at least once. The statement is executed first and then the conditional expression is evaluated to decide upon further iteration.
Thus, the body of a while loop is executed zero or more times, and the body of a do-while loop is executed one or more times.

The general form of do-while is :


initialise loop counter ;
do
{
Statements to be execute ;
.
.
Increment/decrement loop counter ;
}
while ( test condition  ) ;
where,
» Initilise loop counter value will initialize the beginning of the loop.
» The test condition may be any expression and true is any nonzero value.
» The statement is either an empty statement, a single statement, or a block of statements which will be executed if the condition is true.
» The Increment/decrement loop counter will increase or decrease the iteration value as per requirement.

Diagram to show the functionality of The do-while loop

Flow diagram to show the functionality of do while Loop

Some Inportant points about do while Loop:

1. Although the curly braces are not necessary when only one statement is present, they are usually used to avoid confusion (to you, not the compiler) with the while. The do-while loop iterates until condition becomes false.
2. It is good form to always put braces around the do-while body, even when it consists of only one statement. This prevents the while part from being mistaken for the beginning of a while loop.

C Program to show the use of do-while Loop

\* C Program to show the use of do-while Loop *\
# include < stdio.h >
int   main( )
{

int   i  ;
i = 0 ;/* initialise loop counter */
do
{

printf("\n %d ",   i) ;
i = i + 1 ;/* Increment of loop counter */

}
while ( i < = 10  ) ;/* Check condition */
return ( 0 );

}