PfN: season 2 LOops



When a few code lines are repeated until a condition is false, it is called a loop. There are three main types of loops

  • for loop
  • while loop
  • do-while loop. 

1. For loop

syntax : 

for( exp 1; exp 2; exp 3)

{

body;

}

How computer or compiler reads for loop?

In the following order

expression 1 > expression 2 > body > expression 3 in the 1st go.

From 2nd time and onward: expression 2 > body > expression 3. This continues as long the given condition is true.

Moving on to the properties of each expression. 

  • exp 1: You can initialize as many variables as you want, and this expression is optional. 
  • exp 2: This expression holds the condition when false results in the loop's termination. Quite surprisingly, this expression is also optional. You can initialize variables as well as increment or decrement the variables. If only expression 2 is 0, then the expression is false, and the loop shall terminate. 
  • exp 3: Here, you will either increment or decrement the variables, and it can do that for more than one variable simultaneously. Expression 3 is also optional. 
Example 1:






                                                                         Output 1:


Example 2:
In the above example, exp 1 has two variables initialized and hence the corresponding output.


                                                              Output 2:

Here, you can see every for loop expression has everything twice. 2 variables have been initialized, 2 conditional statements and decrement & increment parameters. 
Expression 2 checks two conditions at a time and then the value is printed. If either of them is false then the loop terminates. 

2.  While loop. 

syntax: 

while(exp){

body;

}

Properties: 

  • exp is where the condition goes. If the expression or condition false, i.e. 0 then the loop terminates.
  • Unlike for loop here condition must.
  • More than one conditional expression can be written. 

3. Do-while loop

syntax: 

do{

body;} while ( exp) ;

Properties of the do-while loop are the same as while loop except it loop will be executed at least once. Why? Because compiler will first read the loop body then check the condition or expression. 


Comments

Popular Posts