PHP do-while loop

PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the code.

The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.

Syntax

do{  
//code to be executed  
}while(condition); 

Flowchart

flowchart of php do while loop

Example

<?php    
$n=1;    
do{    
echo "$n<br/>";    
$n++;    
}while($n<=10);    
?>    

Output:

1
2
3
4
5
6
7
8
9
10

Example

A semicolon is used to terminate the do-while loop. If you don’t use a semicolon after the do-while loop, it is must that the program should not contain any other statements after the do-while loop. In this case, it will not generate any error.

 <?php  
    $x = 5;  
    do {  
        echo "Welcome to protutorials! </br>";  
        $x++;  
    } while ($x < 10);  
?>  

Output:

Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!
Welcome to protutorials!

Example

The following example will increment the value of $x at least once. Because the given condition is false.

 <?php  
    $x = 1;  
    do {  
        echo "1 is not greater than 10.";  
        echo "</br>";  
        $x++;  
    } while ($x > 10);  
    echo $x;  
?>

Output:

1 is not greater than 10.
2

Difference between while and do-while loop

while Loopdo-while loop
The while loop is also named as entry control loop.The do-while loop is also named as exit control loop.
The body of the loop does not execute if the condition is false.The body of the loop executes at least once, even if the condition is false.
Condition checks first, and then block of statements executes.Block of statements executes first and then condition checks.
This loop does not use a semicolon to terminate the loop.Do-while loop use semicolon to terminate the loop.

PHP For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.

It allows users to put all the loop related statements in one place. See in the syntax given below:

Syntax

  1. for(initialization; condition; increment/decrement){  
  2. //code to be executed  
  3. }  

Parameters

The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:

initialization – Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.

condition – Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.

Increment/decrement – It increments or decrements the value of the variable.

Example

<?php    
for($n=1;$n<=10;$n++){    
echo "$n<br/>";    
}    
?>

Output:

1
2
3
4
5
6
7
8
9
10

Example

All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don’t pass parameters, it will execute infinite.

<?php  
    $i = 1;  
    //infinite loop  
    for (;;) {  
        echo $i++;  
        echo "</br>";  
    }  
?>  

Output:

1
2
3
4
.
.
.

Example

Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

<?php  
    /* example 1 */  
  
    for ($i = 1; $i <= 9; $i++) {  
    echo $i;  
    }  
    echo "</br>";  
      
    /* example 2 */  
  
    for ($i = 1; ; $i++) {  
        if ($i > 9) {  
            break;  
        }  
        echo $i;  
    }  
    echo "</br>";  
      
    /* example 3 */  
  
    $i = 1;  
    for (; ; ) {  
        if ($i > 9) {  
            break;  
        }  
        echo $i;  
        $i++;  
    }  
    echo "</br>";  
      
    /* example 4 */  
  
    for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);  
?> 

Output:

123456789
123456789
123456789
123456789

PHP Nested For Loop

We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only when the outer for loop condition is found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php    
for($i=1;$i<=3;$i++){    
for($j=1;$j<=3;$j++){    
echo "$i   $j<br/>";    
}    
}    
?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop

PHP for each loop is used to traverse array elements.

Syntax

foreach( $array as $var ){  
 //code to be executed  
}  
?>  

Example

<?php  
$season=array("summer","winter","spring","autumn");  
foreach( $season as $arr ){  
  echo "Season is: $arr<br />";  
}  
?>  

Output:

Season is: summer
Season is: winter
Season is: spring
Season is: autumn

PHP If Else

PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

  • if
  • if-else
  • if-else-if
  • nested if

PHP If Statement

PHP if statement allows conditional execution of code. It is executed if condition is true.

If statement is used to executes the block of code exist inside the if statement only if the specified condition is true.

Syntax

if(condition){  
//code to be executed  
} 

Flowchart

php if statement flowchart

Example

<?php  
$num=12;  
if($num<100){  
echo "$num is less than 100";  
}  
?>  

Output:

12 is less than 100

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.

Syntax

if(condition){  
//code to be executed if true  
}else{  
//code to be executed if false  
}  

Flowchart

php if-else statement flowchart

Example

<?php  
$num=12;  
if($num%2==0){  
echo "$num is even number";  
}else{  
echo "$num is odd number";  
}  
?>  

Output:

12 is even number

PHP If-else-if Statement

The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement.

Syntax

if (condition1){    
//code to be executed if condition1 is true    
} elseif (condition2){      
//code to be executed if condition2 is true    
} elseif (condition3){      
//code to be executed if condition3 is true    
....  
}  else{    
//code to be executed if all given conditions are false    
}  

Flowchart

php if-else statement flowchart

Example

<?php  
    $marks=69;      
    if ($marks<33){    
        echo "fail";    
    }    
    else if ($marks>=34 && $marks<50) {    
        echo "D grade";    
    }    
    else if ($marks>=50 && $marks<65) {    
       echo "C grade";   
    }    
    else if ($marks>=65 && $marks<80) {    
        echo "B grade";   
    }    
    else if ($marks>=80 && $marks<90) {    
        echo "A grade";    
    }  
    else if ($marks>=90 && $marks<100) {    
        echo "A+ grade";   
    }  
   else {    
        echo "Invalid input";    
    }    
?>

Output:

B Grade

PHP nested if Statement

The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.

Syntax

   

if (condition) {    
//code to be executed if condition is true   
if (condition) {    
//code to be executed if condition is true    
}    
}

Flowchart

php if-else statement flowchart

Example

<?php  
               $age = 23;  
    $nationality = "Indian";  
    //applying conditions on nationality and age  
    if ($nationality == "Indian")  
    {  
        if ($age >= 18) {  
            echo "Eligible to give vote";  
        }  
        else {    
            echo "Not eligible to give vote";  
        }  
    }  
?>  

Output:

Eligible to give vote

PHP Switch Example

<?php  
              $a = 34; $b = 56; $c = 45;  
    if ($a < $b) {  
        if ($a < $c) {  
            echo "$a is smaller than $b and $c";  
        }  
    }  
?> 

Output:

34 is smaller than 56 and 45

JavaScript for Loop

JavaScript for Loop is used to execute a particular code block multiple times until a given condition holds true or until all the elements of a given JavaScript object like Array or List are completely traversed.

There are times when we would want to perform a certain operation a certain number of times, like if we have a list of employees with their salaries and we have to calculate their income tax. Now the formula for getting the income tax is the same for all employees, so we can have a loop and execute the code statements with different inputs.

Similarly, for a use case like printing the mathematical table of a number like 2, we can simply have a loop in place to keep on multiplying the number with 1, 2, 3, 4, and so on till 10, incrementing the multiplication factor every time.

The number of times a group of statements is executed depends on a condition provided in the loop, or if we are using the for loop to traverse an array, list, etc, then the loop executes until complete traversal.

The loop statements are executed until the condition becomes false. When the condition becomes false, the execution of loop stops.

In JavaScript, there are various types of loops.

  • for loop
  • for-in loop
  • for-of loop
  • while loop
  • do-while loop

In this tutorial, we will cover the first three loops and we will cover the other in the next tutorial.

JavaScript for Loop

If you want to execute statements for a specific number of times then you can use the JavaScript for loop, which lets you iterate the statements for a fixed number of times.

The for loop consists of three statements to work:

  • initialization: here, the loop counter is initialized with its initial value.
  • condition: here, the condition statement is provided which is checked each time with respect to the value of the counter to continue the iteration.
  • iteration: this statement lets you decide whether you want to increase or decrease the initial counter value also known as increment/decrement.

JavaScript for Loop: Syntax

Following is the syntax for the for loop:

for(initialization; condition; iteration)
{
    // statements
}

The idea here is to initialize a counterset a condition until which the loop will run, and keep on incrementing or decrementing the counter so that after certain iteration the condition fails, and the loop exits. If the condition never fails, the loop will keep on executing infinitely.

JavaScript for Loop: Example

Let’s take an example to see how the loop works,

// for loop example
            for(let a = 0; a < 10; a++) {
               document.write("Current value : " + a);
               document.write("<br>");
            }

JavaScript for...in Loop

If you want to loop through the properties of a JavaScript Object then you can use the JavaScript for…in loop. The for/in loop automatically iterates over the fields of an object and the loop stops when all the fields are iterated.

JavaScript for/in Loop: Syntax

Let’s see the syntax for using the for/in loop in JavaScript.

for(key in object)
{
    // code statements
}

When the loop will run, every time the key will get the value of the key using which we can access the value against it in the object. In JavaScript, objects are in format {“key1″:”value1″,”key2″:”value2”, …} for which the for/in loop can be used to iterate over all the fields of JavaScript object.

JavaScript for...in Loop: Example

Let’s take an example to see it in action,

<h2>for/in loop in JavaScript</h2>
        <p id="demo"></p>
        
            let txt = '';
            // define an object
            let person = {fname:"ram", lname:"singh", age:89};
            let x;
            for(x in person)
            {
                // x is the key like fname, lname and age
                txt += person[x] + " ";
                
            }
            document.getElementById("demo").innerHTML = txt;

JavaScript for...of Loop

The JavaScript for/of loop lets you loop through the values of an iterable object like an array, strings and more.

JavaScript for...of Loop: Syntax

The syntax for the for/of loop in JavaScript is similar to that of for/in loop.

for(variable of iterable)
{
    //code here
}

JavaScript for...of Loop: Example

Below is an example in which we will traverse an array using the for/of loop.

let abc = ['BMW','FERARI','VOLVO'];
let y;
for(y of abc)
{
    document.write(y+,"<br>");
}

In this tutorial, we explained for loop, for/in loop, for/of loop used in the JavaScript. We have explained how this can be used to execute statements in a simple for loop, then iterating over JavaScript object and iterating over array, etc. In the next tutorial we will learn about while and do...while loop.

JavaScript while Loop and do-while Loop

Whenever you want to execute a certain statement over and over again you can use the JavaScript while loop to ease up your work. JavaScript while loop lets us iterate the code block as long as the specified condition is true. Just like for Loop, the while and do...while loop are also used to execute code statements multiple times based on a condition.

The only difference between the while loop and do...while loop is that the do...while loop will execute at least once because in do...while loop the condition is checked after execution of code block.

JavaScript while Loop: Syntax and Use

Below is the syntax for the while loop:

while(condition)
{
    // code statements
}

Let’s take an example to see the while loop in action.

JavaScript while Loop: Example

In this example, we are using while loop, and the loop executes only if the specified condition is true.

let a = 9;
            // while loop will be executed two times
            while (a <= 10)
            {
                document.write("while executed <br>");
                a++;
            }

JavaScript do…while Loop: Syntax and Use

Just like the while loop, the do...while loop lets you iterate the code block as long as the specified condition is true. In the do-while loop, the condition is checked after executing the loop. So, even if the condition is true or false, the code block will be executed for at least one time.

Below we have the syntax of the do...while loop,

do
{
    // code statements
}
while(condition)

JavaScript do...while Loop: Example

Let’s take an example and see the do...while loop in action.

let a = 10;
            // will execute twice
            do 
            {
                document.write("do executed <br>");
                a++;
            }
            while(a < 12)

In this tutorial, we explained the while and do...while loops used in the JavaScript.

JavaScript if, else and else if Statements

In JavaScript, to control the flow of your program or script based on conditions, we can use the if...else conditional statements. The if and else conditional statement works just like they are used in real worl while communicating. For example, see the following statement, if you score more than 40% marks you will pass the exam else you will fail in the exam, here the condition is score more than 40%, if it’s true then you pass, if it is false then you fail.

In JavaScript, if is a conditional statement that is used to control the program flow just like in C, C++, etc programming languages. It is one of the most basic and simplest way to control the flow of program based on conditions. You can use the ifstatement when we want to execute code statements only when a particular condition is true.

The condition for the ifstatement is enclosed within the parenthesis immediately after the ifkeyword.

JavaScript if: Syntax and Use

Below we have the basic syntax for using the if statement in the JavaScript code.

if(<EXPRESSION>)
{
    // block of statements
}

The condition passed with the if statement is mostly an expression that can have comparison of two values, any expression returning boolean output true/false, or any other expression. Also, the condition will be satisfied when the expression returns true or any positive numeric value, and in that case, the block of code statements enclosed within the curly braces below the if statement will be executed.

JavaScript if statement working

JavaScript if Example

In this example, we are using if statement and the if block will be executed only if the expression is true.

let a = 2;
           if(a <= 5)
           {
               document.write("if statement executed");
           }

Now let’s see how does the combination of if...else block works in JavaScript.

JavaScript if...else: Syntax and Use

JavaScript if statement lets you to create a code block with a condition and if the specified condition is true then code statements written inside the if block will get executed. The else statement also creates a code block that is only executed when the specified condition in the if statement is false.

if(<EXPRESSION>)
{
    // if block
}
else
{
    // else block
}

The else statement is always used along with the if statement right after the if block. We cannot provide a condition/expression with the else statement like we do with the if statement.

JavaScript if...else statement working

JavaScript if...else Example

In this example, we will be using an else block along with and if statement and block.

let a = 8;
            if(a <= 5) {
                document.write("if block executed");
            }
            else 
            {
                document.write("else block executed");
            }

Now that we have learned how to use if...else statements, we can make our script execute different code statements based on different conditions. But wait, what if we have more than one condition in our logic, then? Should we use multiple if blocks? The answer to this is covered in the next section.

JavaScript if…else if: Syntax and Use

JavaScript else if statement is used along with the if statement to define multiple different conditions and code blocks. When we have to implement multiple conditions in our script then we can use the ifelse if and else statements in our code. The else if statement is used between the if and else statement, where else is not mandatory.

Below we have the basic syntax of using else if along with if and else statements.

if(EXPRESSION1)
{
    // if block
}
else if(EXPRESSION2)
{
    // else if block
}
else if(EXPRESSION3)
{
    // another else if block
}
else
{
    // else block
}

We can have as many else if block as we want after the if statement. Also, having an else block at the end is optional.

JavaScript else if statement working

JavaScript if...else if Example

In this example, we will be using if and else if statement to test multiple conditions.

let  a = 8;
            if(a < 8)
            {
               document.write("Number is less than 8");
            }
            else if (a = 8)
            {
                document.write("Number is equal to 8");
            }
            else {
                document.write("Number is greater than 8");
            }

And with this, we have finished the JavaScript flow control basics and now we know how we can implement condition-based code execution in our JavaScript code. For example, if you want to write a simple script where you have an HTML form and you ask the user to provide their details like name and gender. Then based on what they enter, you can show a custom message for different gender or similarly based on any other set of conditions you can perform different operations in your user interface using JavaScript.

C++ While and do-while loop

In this tutorial, we will learn the use of while and do…while loops in C++ programming with the help of some examples.

In computer programming, loops are used to repeat a block of code.

For example, let’s say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.

That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.

There are 3 types of loops in C++.

  1. for loop
  2. while loop
  3. do...while loop

In the previous tutorial, we learned about the C++ for loop. Here, we are going to learn about while and do...while loops.


C++ while Loop

The syntax of the while loop is:

while (condition) {
    // body of the loop
}

Here,

  • while loop evaluates the condition
  • If the condition evaluates to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition evaluates to false, the loop terminates.

To learn more about the conditions, visit C++ Relational and Logical Operators.


Flowchart of while Loop

C++ while loop flowchart
Flowchart of C++ while loop

Example 1: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1; 

    // while loop from 1 to 5
    while (i <= 5) {
        cout << i << " ";
        ++i;
    }
    
    return 0;
}

Run Code

Output

1 2 3 4 5

Here is how the program works.

IterationVariablei <= 5Action
1sti = 1true1 is printed and i is increased to 2.
2ndi = 2true2 is printed and i is increased to 3.
3rdi = 3true3 is printed and i is increased to 4
4thi = 4true4 is printed and i is increased to 5.
5thi = 5true5 is printed and i is increased to 6.
6thi = 6falseThe loop is terminated

Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number;
    int sum = 0;

    // take input from the user
    cout << "Enter a number: ";
    cin >> number;

    while (number >= 0) {
        // add all positive numbers
        sum += number;

        // take input again if the number is positive
        cout << "Enter a number: ";
        cin >> number;
    }

    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Run Code

Output

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

In this program, the user is prompted to enter a number, which is stored in the variable number.

In order to store the sum of the numbers, we declare a variable sum and initialize it to the value of 0.

The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.


C++ do…while Loop

The do...while loop is a variant of the while loop with one important difference: the body of do...while loop is executed once before the condition is checked.

Its syntax is:

do {
   // body of loop;
}
while (condition);

Here,

  • The body of the loop is executed at first. Then the condition is evaluated.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • The condition is evaluated once again.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • This process continues until the condition evaluates to false. Then the loop stops.

Flowchart of do…while Loop

C++ do...while loop flowchart
Flowchart of C++ do…while loop

Example 3: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1; 

    // do...while loop from 1 to 5
    do {
        cout << i << " ";
        ++i;
    }
    while (i <= 5);
    
    return 0;
}

Run Code

Output

1 2 3 4 5

Here is how the program works.

IterationVariablei <= 5Action
 i = 1not checked1 is printed and i is increased to 2
1sti = 2true2 is printed and i is increased to 3
2ndi = 3true3 is printed and i is increased to 4
3rdi = 4true4 is printed and i is increased to 5
4thi = 5true5 is printed and i is increased to 6
5thi = 6falseThe loop is terminated

Example 4: Sum of Positive Numbers Only

// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number = 0;
    int sum = 0;

    do {
        sum += number;

        // take input from the user
        cout << "Enter a number: ";
        cin >> number;
    }
    while (number >= 0);
    
    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Run Code

Output 1

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

Here, the do...while loop continues until the user enters a negative number. When the number is negative, the loop terminates; the negative number is not added to the sum variable.

Output 2

Enter a number: -6
The sum is 0.

The body of the do...while loop runs only once if the user enters a negative number.


Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the memory is full). For example,

// infinite while loop
while(true) {
    // body of the loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop

int count = 1;

do {
   // body of loop
} 
while(count == 1);

In the above programs, the condition is always true. Hence, the loop body will run for infinite times.


for vs while loops

for loop is usually used when the number of iterations is known. For example,

// This loop is iterated 5 times
for (int i = 1; i <=5; ++i) {
   // body of the loop
}

Here, we know that the for-loop will be executed 5 times.

However, while and do...while loops are usually used when the number of iterations is unknown. For example,

while (condition) {
    // body of the loop
}

C# Loop control statements

Break

The C# break is used to break loop or switch statement. It breaks the current flow of the program at the given condition. In case of inner loop, it breaks only inner loop.

C# Break Statement Example

using System;
public class BreakExample
{
public static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4

Continue

The C# continue statement is used to continue loop. It continues the current flow of the program and skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.

C# Continue Statement Example

using System;
public class ContinueExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

Goto

The C# goto statement is also known jump statement. It is used to transfer control to the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

Currently, it is avoided to use goto statement in C# because it makes the program complex.

C# Goto Statement Example

using System;
public class GotoExample
{
public static void Main(string[] args)
{
ineligible:
Console.WriteLine(“You are not eligible to vote!”);

Console.WriteLine(“Enter your age:\n”);
int age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
goto ineligible;
}
else
{
Console.WriteLine(“You are eligible to vote!”);
}
}
}
output:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!