Loops in c 1

Loops in C – I

What is while loop?

This is used to repeat the code any number of times. It relays on the condition given on how many times to be repeated. This falls under pre-test loops.

Syntax:

initialization;

while(condition)

{

// loop body

increment/decrement;

}

What is do while loop?

This is used to repeat the program any number of time according to the condition given. This falls under post-test loops that is, the body is executed and incremented/decremented firstly, and then the condition is checked.

Syntax:

initialization;

do

{

// loop body

increment/decrement;

}

while(condition);

What is the difference in while loop and do while loop?

WHILE LOOP 

-> This is a pre-test loop.

-> First iteration is done after the condition is verified. Output is given if true, and not given if false.

-> Example:

a=4;

while(a>5)

{

printf(“a = %d”,a);

a++;

}

Output: NULL

DO WHILE LOOP

-> This is a post-test loop.

-> Condition is checked after the first iteration is done. Output is given whether true or false and then the condition is verified followingly.

Example:

a=4;

do

{

printf(“a = %d”,a);

a++;

} while(a>5)

Output: 5

Note: The difference is well explained by the example. The same program gives not output for while loop whereas gives some output for do while.