C do - while loop

Programming languages or concepts
0
In this tutorial, you will learn how to create while looping in C programming with the help of examples.
In programming, a loop is used to repeat a block of code until the specified condition is met.

C programming consists of three types of loops.

  1. For the loop
  2. While the loophole
  3. do ... while loop

 C do-while loop

in  do - while loop it checks the condition at the bottom of the loop.

The do while loop statements is a post tested loop. Using the do-while loop, we can re-execute different parts of the statement. The do-while loop is mainly used in menu driven programs where the closing condition depends upon the end user.

We use do while loop mainly where we want to execute condition or loop at least once

do while loop is same as while loop but it has one exception,  it executes the statements inside the body of do while before checkin the condition. on the other side,  in while loop first the condition is checked and then the statements in while loop are executed. So you can say that if a condition is wrong in the first initial phase then do while will only work once, however while loop will not work at all.


C – do..while loop

Syntax of do-while loop || do while syntax :-

do
{
    //Statements 

}while(condition test);

Notice that the conditional expression appears at the end of the loop, so the statement (s) in the loop is executed once before the condition is checked.

If the condition is true, the control flow goes back up and the statement (s) in the loop is reactivated. This process is repeated until the given condition is false.

How does a do-While loop executes? 

 

  1. Control comes in a do-while loop.
  2. The statements in the main part of the loop are executed.
  3. Updation happens.
  4. The flow goes on condition
  5. Condition is tested. 
  6. If the condition is true, go to step 6.
  7. If the condition is wrong, the flow goes out of the loop
  8. The flow goes back to step 2.

Flow diagram of do while loop

do while loop in c


Example of do while loop


#include <stdio.h>
 
int main () {
 
   /* local variable definition */
   int a = 1;
 
   /* do loop execution */
   do {
      printf("value of a: %d\n", a);
      a = a + 1;
   }while( a <= 20 );
 
   return 0;
}



While the loop is working ... how to do it?

The loop is run only once while the main part of the dua is ... Only then, testExpression is evaluated.
If testExpression is true, the main part of the loop is reactivated and testExpression is re-evaluated.
This process continues until the testExpression fails.
If testExpression is false, the loop ends.

Post a Comment

0Comments

Post a Comment (0)
close