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 foreach loop

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.

In foreach loop, we don’t need to increment the value.

Syntax

foreach ($array as $value) {  
    //code to be executed  
}  

There is one more syntax of foreach loop.

Syntax

foreach ($array as $key => $element) {   
    //code to be executed  
}  

Flowchart

php for loop flowchart

Example 1:

PHP program to print array elements using foreach loop.

<?php  
    //declare array  
    $season = array ("Summer", "Winter", "Autumn", "Rainy");  
      
    //access array elements using foreach loop  
    foreach ($season as $element) {  
        echo "$element";  
        echo "</br>";  
    }  
?>

Output:

Summer 
Winter 
Autumn 
Rainy

Example 2:

PHP program to print associative array elements using foreach loop.

<?php  
    //declare array  
    $employee = array (  
        "Name" => "Alex",  
        "Email" => "alex_jtp@gmail.com",  
        "Age" => 21,  
        "Gender" => "Male"  
    );  
      
    //display associative array element through foreach loop  
    foreach ($employee as $key => $element) {  
        echo $key . " : " . $element;  
        echo "</br>";   
    }  
?> 

Output:

Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male

Example 3:

Multi-dimensional array

<?php  
    //declare multi-dimensional array  
    $a = array();  
    $a[0][0] = "Alex";  
    $a[0][1] = "Bob";  
    $a[1][0] = "Camila";  
    $a[1][1] = "Denial";  
      
    //display multi-dimensional array elements through foreach loop  
    foreach ($a as $e1) {  
        foreach ($e1 as $e2) {  
            echo "$e2\n";  
        }  
    }  
?>  

Output:

Alex Bob Camila Denial

Example 4:

Dynamic array

<?php  
    //dynamic array  
    foreach (array ('p', 'r', 'o', 't', 'u', 't', 'o', 'r', 'i', 'a','l','s') as $elements) {  
        echo "$elements\n";  
    }  
?> 

Output:

p r o t u t o r i a l s

Kotlin while and do…while Loop

Loop is used in programming to repeat a specific block of code. In this article, you will learn to create while and do…while loops in Kotlin programming.

Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false).

Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops.

You will learn about two loops while and do..while in this article with the help of examples.

If you are familiar with while and do…while loops in Java, you are already familiar with these loops in Kotlin as well.


Kotlin while Loop

The syntax of while loop is:

while (testExpression) {
    // codes inside body of while loop
}

How while loop works?

The test expression inside the parenthesis is a Boolean expression.

If the test expression is evaluated to true,

  • statements inside the while loop are executed.
  • then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false.

If the test expression is evaluated to false,

  • while loop is terminated.

Flowchart of while Loop

Kotlin while Loop Flowchart

Example: Kotlin while Loop

// Program to print line 5 times

fun main(args: Array<String>) {

    var i = 1

    while (i <= 5) {
        println("Line $i")
        ++i
    }
}

When you run the program, the output will be:

Line 1
Line 2
Line 3
Line 4
Line 5

Notice, ++i statement inside the while loop. After 5 iterations, variable i will be incremented to 6. Then, the test expression i <= 5 is evaluated to false and the loop terminates.


If the body of loop has only one statement, it’s not necessary to use curly braces { }


Example: Compute sum of Natural Numbers

// Program to compute the sum of natural numbers from 1 to 100.
fun main(args: Array<String>) {

    var sum = 0
    var i = 100

    while (i != 0) {
        sum += i     // sum = sum + i;
        --i
    }
    println("sum = $sum")
}

When you run the program, the output will be:

sum = 5050

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0. For better visualization,

1st iteration: sum = 0+100 = 100, i = 99
2nd iteration: sum = 100+99 = 199, i = 98
3rd iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
99th iteration: sum = 5047+2 = 5049, i = 1
100th iteration: sum = 5049+1 = 5050, i = 0 (then loop terminates)

To learn more about test expression and how it is evaluated, visit comparison and logical operators.


Kotlin do…while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed once before the test expression is checked.

Its syntax is:

do {
   // codes inside body of do while loop
} while (testExpression);

How do…while loop works?

The codes inside the body of do construct is executed once (without checking the testExpression). Then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and test expression is evaluated again. This process goes on until the test expression is evaluated to false.

When the test expression is evaluated to falsedo..while loop terminates.


Flowchart of do…while Loop

Kotlin do...while Loop flowchart

Example: Kotlin do…while Loop

The program below calculates the sum of numbers entered by the user until user enters 0.

To take input from the user, readline() function is used. 

fun main(args: Array<String>) {

    var sum: Int = 0
    var input: String

    do {
        print("Enter an integer: ")
        input = readLine()!!
        sum += input.toInt()

    } while (input != "0")

    println("sum = $sum")
}

When you run the program, the output will be something like:

Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: -6
Enter an integer: 0
sum = 3

Python for Loop

In this article, you’ll learn to iterate over a sequence of elements using the different variations of for loop.

What is for loop in Python?

The for loop in Python is used to iterate over a sequence (listtuplestring) or other iterable objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:
	Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Flowchart of for Loop

Flowchart of for Loop in Python programming
Flowchart of for Loop in Python

Example: Python for Loop

# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
	sum = sum+val

print("The sum is", sum)
	

When you run the program, the output will be:

The sum is 48

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided.

The range object is “lazy” in a sense because it doesn’t generate every number that it “contains” when we create it. However, it is not an iterator since it supports inlen and __getitem__ operations.

This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.

To force this function to output all the items, we can use the function list().

The following example will clarify this.

print(range(10))

print(list(range(10)))

print(list(range(2, 8)))

print(list(range(2, 20, 3)))

Output

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index
for i in range(len(genre)):
	print("I like", genre[i])

Output

I like pop
I like rock
​I like jazz

for loop with else

for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Hence, a for loop’s else part runs if no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]

for i in digits:
    print(i)
else:
    print("No items left.")

When you run the program, the output will be:

0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints No items left.

This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Let’s take an example:

# program to display student's marks from record
student_name = 'Soyuj'

marks = {'James': 90, 'Jules': 55, 'Arthur': 77}

for student in marks:
    if student == student_name:
        print(marks[student])
        break
else:
    print('No entry with that name found.')

Output

No entry with that name found.