do while Loop In C Language

 do while Loop In C Language


What is do while loop in C Language?

The do while loop is similar to the while loop but only one difference is the body of the loop is executed at least once before test expression is evaluated. If the test condition is true then again the body of the loop is executed. The process goes on until the condition is true. When the test condition becomes false the iteration stops. 

 do while  top tested loop and for loop and while loop are bottom tested loop. Do while loop is used in case only when we want to execute a loop only once.


Syntax for do while loop in C: 

do 

{

//Body of loop

}

while(test expression);  // test condition


Working of do while loop:

1. Body of the while loop is executed first then the test expression is evaluated.

2. If the test expression is true then the body of the loop is executed again and the test expression is evaluated again.

3. This iteration process goes on until the condition is true. 

4. When the test condition becomes false then the loop ends.



click here :👉 Flowchart if do while loop





/***************************************************

 C program to demonstrate do while loop 

***************************************************/


#include<stdio.h>

#include<conio.h>

void main()

{

    int i,sum=0;

    printf("do while loop demonstration\n");

    do{

        sum=sum+i;

        i++;

    }

    while(i<=10);

    printf("The sum of first 10 natural numbers is %d\n",sum);

    printf("End of program");

}


do while loop demonstration

The sum of first 10 natural numbers is 55

End of program


Here the body of the loop is executed once i.e. first iteration runs without checking test condition.  The test condition is evaluated only after the first iteration is executed. Then if the test condition is true i.e if the value of i is less than or equals to 10 the iteration will go on. When the value of i becomes 11, iteration will stop. 



टिप्पणी पोस्ट करा

0 टिप्पण्या