What is Do while and For loop? Simple meaning of do while and for loop with examples | Codingclasspoint

do while loop



This (do while loop) statement is also used for looping. The body of this loop may contain single statement or block of statement. The syntax for writing this statement is:

Syntax:


Do 


Statement; 


while(condition); 

Example:

#include 
void main() 
int X=4; 
do 
Printf(“%d”,X); 
X=X+1;
}whie(X<=10); 
Printf(“ ”); 
}

Output: 

4 5 6 7 8 9 10 

Here firstly statement inside body is executed then condition is checked. If the condition is true again body of loop is executed and this process continue until the condition becomes false. Unlike while loop semicolon is placed at the end of while. 

There is minor difference between while and do while loop, while loop test the condition before executing any of the statement of loop. Whereas do while loop test condition after having executed the statement at least one within the loop. 

If initial condition is false while loop would not executed it’s statement on other hand do while loop executed it’s statement at least once even If condition fails for first time. It means do while loop always executes at least once. 

Notes:  Do while loop used rarely when we want to execute a loop at least once


for loop

 In a program, for loop is generally used when number of iteration are known in advance. The body of the loop can be single statement or multiple statements. Its syntax for writing is:

Syntax

for(exp1;exp2;exp3) 

{
 Statement; 

or


for(initialized counter; test counter; update counter) 
{
 Statement; 
}

Here exp1 is an initialization expression, exp2 is test expression or condition and exp3 is an update expression. Expression 1 is executed only once when loop started and used to initialize the loop variables. Condition expression generally uses relational and logical operators. And updation part executed only when after body of the loop is executed.

Example:- 

void main() 
int i; 
for(i=1;i<10;i++) 
Printf(“ %d ”, i); 
 } 
}

Output

1 2 3 4 5 6 7 8 9

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.