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();

Series Navigation<< C#: The do-while statement
C#: For statement optional initialization >>
Posted in

Leave a comment

Leave a Reply