C - Language Theory
Loops
Loop statement are used to repeat the execution of statement or blocks.
Type of Loops
Loops are classified into two types:
1. Entry controlled loop(for loop, while loop).
2. Exit controlled loop(do-while).
For Loop
For Loop
Syntax |
---|
for(initialization statement; test condition; increment/decrement statement) { //statement to be executed repeatedly } |
1. First go for initialization.
2. Second condition
- If the condition is true then statement part is executed and then iteration portion.
- If the condition is false then out of the for-loop.
3. Third Iteration
- After iteration portion control goes back to condition.
While Loop
While Loop
It is an entry-controlled loop. A loop is used for executing a block of statements repeatedly until a given condition returns false.
Syntax |
---|
initialization statement; while (test-condition) { //statements to be executed repeatedly increment/decrement statement } |
Here, statement(s) may be a single statement or a block of statements.
1. First condition is evaluated.
2. If the condition is true then statement part is executed then again it checks the condition.
3. If the condition is false then out of the while loop.
Do-While
Do-While Loop
Syntax |
---|
initialization statement; do { //statements to be executed repeatedly increment/decrement statement } while (test-condition) |
Note: In do while loop the body will execute at least once irrespective of test condition.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
1. First statement part is executed and then the condition part is evaluated.
2. If the condition is true then again statement part executed and then again to the condition part.
3. If the condition is false then out of do-while loop.