Looping


Bounded Loops : A bounded loop executes fixed number of times-when you can tell by looking at the code how many times the loop will iterate.

Unbounded Loops : An unbounded loop repeats until some condition becomes true (or false), and that condition is dependent on the action of the code within the loop.


While

  • The while loop checks the condition expression as a Boolean if it is true, it executes statement and then starts again by evaluating condition.

  • If the condition is false, the while loop terminates.
  • Syntax :
    while (condition)
    {
    	Statement
    }
    


    Do-While

    • The do-while construct is similar to while, except that the test happens at the end of the loop.

    • The statement is executed once, and then the expression is evaluated.

    • If the expression is true, the statement is repeated until the expression becomes false.
    Syntax :
    Syntax:- 
    
    Do
    {
    	Statement
    }	
    while (expression);
    


    For

  • For statement, first the initial-expression is evaluated only for once, to initialize variables.

  • Then termination-check is evaluated if it is false, the for statement ends, and if it is true, the statement executes.

  • Finally, the loop-end-expression is executed and the cycle begins again with termination-check.
  • Syntax :
    for (initial-exp; termination-check; loop-end-exp)
    {
    	Statement
    }
    


    foreach Loop

    The foreach loop is used to loop through arrays.
    Syntax :
    foreach ($array as $value)
    {
    	Statement;
    }
    


    Break and Continue

    • Break is used in terminating the loop immediately after it is encountered.

    • The break statement is used with conditional if statement.

    • The continue command skips to the end of the current iteration of the innermost loop that contains it.
    Example:
    for (initial-exp; termination-check; loop-end-exp)
    {
    	if (Condition)// if it is true
    	break;
    	Statement;
    }