We used loops to execute a block of code several times. do while loop is similar as while loop but in do while loop conditional expression appears at the bottom of the loop instead of the beginning.
Syntax of a While loop
do { // body statement. } while ( Condition );Note
- Before checking the condition do while loop must be executed once.
- Conditional expression / statement appears in the bottom of the loop. And there is a semicolon after the conditional expression.
Condition : After checking the condition it decides whether loop needs to continue or not. If the condition is false then the loop will not be executed.
Let’s look into the following program which will print “Hello world” 5 times.
#include <stdio.h> int main() { int i = 1; do { printf("Hello World \n"); i++; // Update. } while ( i <= 5 ); return 0; }Output
Hello World Hello World Hello World Hello World Hello World
How it works
Step 1 : First it will go to the body statement, there is a print command and it will be executed.
Step 2 : After that, Update statement will be executed
Step 3 : Start repeating from Step 1.
Step 4 : Then it will check either the condition ( i <= 5 ) is true or not. If the condition is true only then it will start repeating (go to the body statement) from Step 1. Otherwise it will be terminated.
No comments:
Post a Comment