Iteration Statements :
2. Test Expression : Its truth value decides whether the loop body will be executed otherwise loop will be terminated.
In an entry controlled loop it is evaluated before entering into a loop and in exit controlled loop it is evaluated before exiting from loop.
3. Update Expression : It changes the value of loop control variables.
4. Body of the loop : Statements that are to be executed in a loop.
Firstly, initialisation expression is evaluated, then, test expression, then body of loop and at last update statement
for Loop :
It is an entry controlled loop and the easiest to understand and implement.
for(initialisation expressions; test expressions; update expressions)
body of the loop
If a for loop executes only once, it will terminate only when the value of its loop variable will cause a false condition.
Optional expression : Initialisation expression, test expression and update expressions are optional i.e. one or all of it can be skipped like if we have already initialised loop variables then Initialisation expression can be skipped.
Infinte loop using for loop : By removing the test expression infinte loop can be created.
Empty loop: The one which doesn’t contain any statement or a null statement only(;).
while Loop :
It is an entry controlled loop.
It is an exit controlled loop i.e. test expression is evaluated before exiting loop body and loop body is executed atleast once even if the test expression is false.
- For loops are appropriate where we know in advance how many times the loop will execute and while and do-while are used where we do not know beforehand how many times the loop is to be executed.
- do-while is used where loop body is executed atleast once irrespective of the test expression being true or false.