This C Tutorial explains the difference between While and Do-while Loop in C Programming.
Do-while Loop in C
In do-while loop, condition is always tested after the execution of the iteration and if condition fails, loop terminates. Therefore, do-while loop executes at least one iteration before termination if condition fails in first iteration!
Do-while loop Syntax:
/* * In do-while: condition is tested in the end of each iteration */ do { statements; } while(condition);
The code inside the do {} block will run until the condition inside the while () statement evaluates to false. When the condition is false, the program will exit the do while loop and continue running any code that follows.
Do While Loop Example
#include <stdio.h> int main(void) { int counter = 0; do { /* loop executes just once printing the value 0 */ printf("counter is %d\n", counter); } while(counter++ != 0); return 0; }
While Loop
In while loop, condition is checked before execution of each iteration and as condition fails, loop terminates.
While Loop Syntax
/* * In while, condition is tested in the beginning of each iteration */ while (condition) { statements; }
While Loop Example:
#include <stdio.h> int main(void) { int counter = 0; /* loop terminates in the beginning of first iteration */ while (counter++ != 0) printf("counter is %d\n", counter); /* here counter val is printed as 1 */ printf("counter is %d\n", counter); return 0; }
Difference between While and Do-while Loop in C
While Loop | Do While Loop |
---|---|
While loop first checks the condition, then executes the statement | Do while loop will run the statement at least once before checking the condition. |
The while loop is an entry control loop. | The do-while loop is an exit control loop. |
A semicolon is not required at the end of a while condition. | At the end of the while condition, we need to add a semicolon. |
The condition is checked at the beginning of each iteration; if it evaluates to false, the loop terminates. | The do-while loop is similar to the while loop, but the condition is checked at the end of each iteration instead of at the beginning. This means that the code inside the do-while loop will always be executed at least once. |
In the case of a single statement, brackets are not necessary. | Brackets are mandatory. |
While Loop Syntax: while (condition) { // Statements } |
Do While Loop Syntax: do { statements; } while(condition); |
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice Computer Science MCQs
- Practice BCA MCQs
- Check C Books