do-while loop (Iteration statement) execute a statement or block of statements until the given condition is true.
Syntax:
do { //do while body } while ( expression ) ;
Flow-chart of the do while loop in C
In the do-while, evaluation of the controlling expression takes place after each execution of the do while body. So, that is the reason body of the do-while is always executed at least once.
How does the do-while loop work?
Step 1. The body of the do-while is executed.
Step 2. Now evaluates the controlling expression. If the controlling expression is false, then control jumps to the next statement in the program (exit from the loop).
Step 3. If the controlling expression is true or any non zero value, then the process is repeated from step 1.
For example,
In the below example, I am printing and calculating the table of 10.
#include <stdio.h> int main () { int data = 10; int loop = 1; /* do while loop */ do { printf(" data * loop = %d\n", (data*loop)); ++loop; } while( loop <= 10 ); return 0; }
Output:
Similar to the while iteration, we can also terminate do while using the break, goto or return keyword. We can also terminate an iteration without exiting the do-while loop using the continue keyword.
for example,
#include<stdio.h> int main() { int loop = 0; do { if(loop == 2) { break; // terminate loop } printf("Value of loop = %d\n", loop); ++loop; } while(loop < 5 ); return 0; }
Output:
Value of loop = 0
Value of loop = 1
When should we use do while loop?
We use the do-while loop where we want to execute the body at least once. Suppose a scenario where the program wants only positive value from the user and wait until the user does not enter the positive value. In that scenario do while is the best choice for the programmer.
See the below sample code,
do { //Get value from the user value = getInputValue(); } while(value < 0)
Recommended Articles for you:
- How to use if condition in C?
- How to use C if-else condition?
- How to use for loop in C?
- You should know while loop use.
- Use of the switch case in the C program.
- C language character set.
- Elements of C Language.
- Data type in C language.
- Operators with Precedence and Associativity.
- How to pass an array as a parameter?
- Memory Layout in C.
- File handling in C, In a few hours.
- Replacing nested switches with the multi-dimensional array
- How to access a two-dimensional array using pointers?
- Brief Introduction of switch case in C.
- 100 C interview Questions.
- Function pointer in c, a detailed guide.
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic in C.
- Brief Introduction of void pointer in C.