C#: The while statement

This entry is part 41 of 71 in the series C#

Following the if else, the next common conditional statement should be the while statement.

In many ocassions, you may want to perform an action several times in a row. In other words, you have a block of code that you want executed repeatedly.

You can perform that using repeated line of of code or you can use a while statement.

The sytax for while statement is:

While (expression)
{
   statement 1;
   statement 2;
}

Similar to if else statement, the expression should resolve to true for the statements to be executed.

The While Statement
using System;

namespace Conditional
{
    class Program
    {
        private int number;

        private Program(int number1)
        {
            number = number1;
        }

        private void checkNumber()
        {
            int number = 0;
            while (number < 3)
            {
                System.Console.WriteLine(number);
                number++;
            }
        }

        static void Main()
        {
            int x = 0;

            Program increment = new Program(x);
            increment.checkNumber();
            Console.ReadLine();
        }
    }
}

The output from running the above code will be 0,1,2.

Javascript: While loop

This entry is part 16 of 27 in the series Javascript Tutorial

The while statement creates a loop that executes a specified statement as long as the test condition is true.

<!DOCTYPE html>
<html>
<head>
    <title>While</title>
    <script>
        function myFunction() {
            var n = 0;
            var x = 0;
            while (n < 3) {
                n = n+1;
                x = x+n;
                document.getElementById("id_n").innerHTML = n;
                document.getElementById("id_x").innerHTML = x;
            }
        }
    </script>
</head>
<body>
<p id="id_n">n</p>
<p id="id_x">x</p>
<br>
<button onclick="myFunction()">Click Me</button>
</body>
</html>
Try The Code  

As n starts with 0 and the condition is (n < 3), while loop will run 3 times and the n will evaluate to 3 and x will evaluate to 1+2+3=6.

 

PHP: While loop

This entry is part 27 of 54 in the series PHP Tutorial

While loops are the simplest type of loop in PHP.

The basic form of a while statement is:

while (expression)
    statement

The meaning of a while statement is simple.

It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.

The value of the expression is checked each time at the beginning of the loop.

<?PHP
$i = 1;
while ($i <= 10) {
    echo $i;
    $i = $i + 1;  
    echo "\n";
   }
?>

There are 3 statements in the while loop.  The condition is while $i <= 10, the 3 statements will be ran.

$i is increased by 1 each time the loop is ran and the condition will be checked after it is increased by 1.