LOOP STATEMENTS

Loop statements are used when we want to execute some line of code repeatedly. 
For loops are used when we know the number of times we run the loop. 
while loops are used when we are not sure about the number of times we run the loop.

Syntax:
FOR loop:
for(counter_variable initialization;for_condition; counter_variable increment/decrement)
{
        statements;
}

In For loop parenthesis we have three parts. First is for initialisation, Second is for condition and third is to increment or decrement  the counter variable.

First the variable is initialised. Then the condition is checked. If the condition evaluates to be true then compiler will execute the statements inside the loop block. after execution, it will increment/decrement the counter variable and will check the condition again. if condition is true then executes the block statements, otherwise the flow of control comes out of the loop and continues to execute the statements outside the loop.


WHILE loop:

while(while_condition)
{
      statements;
}

Similarly in WHILE loop also, first the condition is evaluated. If it is true then statement inside the block are executed else loop is terminated. After executing the statements inside the loop compiler will check for the while condition.

Note:Make sure you write a condition such that the while loop terminates after sometime.Otherwise you might encounter an infinite loop(the program never ends)


Do WHILE loop:
do
{
      statements;
}while(while_condition);



In DO WHILE loops, the while condition is evaluated after executing the statements for the first time. Therefore, in Do while loops even if the condition evaluates to be false the statements are executed once.


Note: In both types of loops we need to take care of termination condition. Otherwise, the loop runs infinitely many times(😈).

Example
Code:

Output:



Leave a Reply