2.2 Control statements ( Iterative or looping control statements)
3) Iterative control structures: -
- Iterative control structure is also called as looping control statements.
- Looping control statements are used to execute a block of code repeatedly as long as a given condition is true.
- Instead of writing the same code multiple times, loops help avoid writing repetitive code.
- Loop declaration and execution can be done in the following ways:
- Check the condition to start a loop.
- Initialize the loop with declares a variable.
- Executing the statements inside a loop.
- There are three main types of loops in C:
a) for loop.
b) while loop.
c) do while loop.
a) For loop:
-
- For loop a best looping control structure which is used to execute the statement repeatedly as long as a given condition is true.
- The for loop is used when the number of iterations is known to execute a block of code.
- In for loop, first initialization is done, Next the condition is checked.
- If the condition is true, the statements
inside the loop are executed. After execution, the variable will increase or
decrease by one. After this total process, again the condition is going to
check. This process will continue as long
as a given condition is true.
Syntax: -
Flow
chart: -
Example: -
Output: -
b) While loop: -
- While loop is a looping statement which is used to execute the statement as long as the condition is true.
- It is used when the number of iterations is not known in advance.
- In while loop, the condition is checked first.
- If the condition is true then statement under while loop gets execute.
- If the condition is false then the while block statements are ignored. So, this reason while loop is called entry-control loop.
- While loop statement doesn’t have semi colon ;
Syntax: -
Flow chart: -
Example: -
Output: -
c) Do while
loop: -
- The do-while loop is a looping control statement which is used to execute the statements as long as the condition is true otherwise the repetition will stop.
- Do while loop is executed at least once without checking any condition. So, it is also known as “exit control loop” or “Bottom Testing Loop”.
- Semi colon ; is placed at the end of the while statement.
- If the condition true, again the statement get executed. These will continue as long as the condition is true.
Syntax: -
Flow chart: -
Example: -
Output: -