Java: For each loop

This entry is part 11 of 54 in the series Learn Java

The for each loop gives an easy way to iterate through arrays.

On each iteration the next element in the array is assigned to the specified variable, and the loop continues to execute until it has gone through the entire array.

package javaapplication9;

public class JavaApplication9 {

    public static void main(String[] args) {

        int[] array = {1, 2, 3, 4, 5};
        
        for (int element : array) {
            System.out.print(element);
        }
        System.out.println();
    }
}

foreach

C#: The for statement

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

The for statement is like the while statement, i.e. you use it to enclose code that needs to be executed multiple times.

The for statement starts with an initialization, followed by an expression evaluation for each iteration and the execution of a statement block if the expression evaluates to true.

An update statement will also be executed after the execution of the statement block for each iteration.

The for statement has following syntax.  It has the same syntax as C, C++, Java but not PASCAL.

for (init; Expression; update) 
{
    statements;
}

Here, init is an initialization that will be performed before the first iteration.

Expression is a boolean expression which will cause the execution of statement(s) if it evaluates to true, and update is a statement that will be executed after the execution of the statement block.

Below here an example.

using System;

namespace Conditional
{
    class Program
    {
        private static void checkNumber()
        {
            for (int number = 0; number < 3; number++)
            {
                Console.WriteLine(number);
            }
        }

        static void Main()
        {
            Program.checkNumber();
            Console.ReadLine();
        }
    }
}

Static Method In This Example

Notice that there is no variable in the class Program.  For a class without variables, you can consider declaring the methods to be static as in this example.

With static method, you can access the method without declaring an instance.

Here, I access the checkNumber method using class name Program.

Program.checkNumber();

Posted in