03.c] Compare the working of for, while, and do While along with their syntax.
Answer:-
i. while loop:
➢ It is a pre-test loop (also known as an entry controlled loop).
syntax:
while (condition) { statement-block; }
➢ In the syntax given above ‘while’ is a key word and condition is at beginning of the
loop.
➢ If the test condition is true the body of while loop will be executed.
➢ After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.
➢ This process is repeated until condition finally becomes false and control comes out of the body of the loop.
Flow Chart:-
ii. do…. while loop:
It is a post-test loop (also called exit controlled loop) it has two keywords do and while.
Syntax:
Do { statement-block; } while (condition);
➢ In this loop, the body of the loop is executed first and then the test condition is evaluated.
➢ If the condition is true, then the body of the loop will be executed once again. This process continues as long as the condition is true.
➢ When the condition becomes false, the loop will be terminated and control comes out of the loop.
Flow Chart:-
iii. for loop:
➢ It is another pre-test loop (also called entry controlled loop) that provides a concise loop control structure. It has one keyword called for.
➢ One important aspect of for loop is all the three components of a loop (viz. initializing, testing condition, and updating (increment/decrement)) is given in the head of for loop.
Syntax:-
for( initialization; test-condition; updation) { Body-of loop; }
- In this loop first initialization of control variable is done first, using assignments such as i=1, count=0. The variable i count are called loop control variable.
- The value of control variable is tested using the test condition. The test condition is evaluated. If the condition is true, the body of the loop is executed; otherwise loop will be terminated.
- When the body of the loop is executed, the control transferred back to the for statement to update the loop variable. And then condition is checked once again. If condition is true once again body will be executed once again. This process continues till the value of the control variable fails to satisfy the test condition.
Flow Chart:-