C# for Loop

C# For loop graphical illustration

Using for loop in C#

The C# for loop is a way to execute a block of code to the specified number of times.
for (int i = 1; i <= 5; i++)
  {
    Console.WriteLine(i);
   }

The statements inside the for loop keep on executing until the condition is false.

Syntax of using for loop

This is how you may use the for loop in C#:

for ( initialize_expression; condition; iterator ) {

// code to be executed here;

}

The parts of the for loop in the above syntax are explained below:

Loop Part Description
initialize_expression
  • First of all, the initialize_expression is once executed even before entering the for loop.
  • This expression can be the declaration and initialization of a variable. e.g.:

int x = 1;

  • This variable cannot be accessed from outside of the for loop.
  • Similarly, the expression can be an object with the new keyword, an await expression, an invocation of a method, etc.
  • This is an optional section in for loop.
condition 
  • The condition part which is a Boolean expression is also optional in the for loop. For example:

x >= 100;

  • The loop keeps on executing as long as the condition is evaluated as True or this optional part is not given
  • As the condition becomes False, the loop exits and control moves to the next line of code outside of the loop.
iterator
  • The third section in the for loop is an iterator.
  • This is also optional.
  • There, you may specify what to do after each iteration. For example, increment a variable:

x = x + 1;

x++

  • Or decrement a variable:

X = x – 1;

x–;

  • Similarly, you may use the assignment statement, await expression, create an object by the new keyword, or invocate a method there.

An example of for loop with increment operator

In this example, we will display the value of variable x in each iteration of the loop.

In the initialize section, the variable x is declared with an initial value of 10.

The second part, condition, is set as the value of variable 100 or less.

The third part (iterator) is set to increase the value of x by 10.

Have a look at the code and output:

using System;

class for_loop_demo
{
    static void Main()
    {
        for (int x = 10; x <= 100; x = x + 10)
        {
            Console.WriteLine("value of X = " +x);
        }
        Console.ReadLine();
    }
}

Output:

value of X = 10
value of X = 20
value of X = 30
value of X = 40
value of X = 50
value of X = 60
value of X = 70
value of X = 80
value of X = 90
value of X = 100

The example with the decrement operator

The example below uses decrement in the iterator section. So, this time variable x value is set as 50 and in each iteration, its will be subtracted by 5. The value of x is displayed in each iteration to show the current value:

using System;
class for_loop_demo_decrement
{
    static void Main()
    {
        for (int x = 50; x >= 0; x = x - 5)
        {
            Console.WriteLine("value of X = " +x);
        }
        Console.ReadLine();
    }
}

c# for-loop-decrement

Using break statement in for loop example

The break statement can be used in the for loop for exiting the loop entirely. As soon as the break statement is executed, the for loop quits and the control moves to the next line outside of the loop.

Note: If you only want to quit the current iteration rather than quitting the loop entirely, use the continue statement (see next example).

In the following example, we have an array of numbers.

In the for loop, I used a for loop to iterate through a C# array. In the condition section, the length method of the array is used.

Inside the loop body, the if condition is used to check the current element value.

If this is equal to 10 then the break statement will execute to exit the loop:

using System;

class for_loop_demo_break

{
    static void Main()
    {
        int[] arr_nums = { 2, 4, 6, 8, 10, 12, 14, 17, 20, 22 };

        for (int x = 0; x < arr_nums.Length; x++)
        {
            Console.WriteLine(arr_nums[x]);

            if (arr_nums[x] == 10)
            {
                Console.WriteLine("The value of current array element is 10, so it will quit!");
                break;
            }
        }
        Console.ReadLine();
    }
}

The result:

24
6
8
10
The value of current array element is 10, so it will quit!

Get the leap years by using continue in for loop

As said earlier, for exiting the current iteration only, you may use the continue statement in C#. To demonstrate that, we have an array of years.

By using the for loop with the continue and if statements, we will get the leap years and display it on the screen.

The array contains the following years:

{ 1992, 1994, 1996, 2000, 2002, 2008, 2010, 2012, 2016, 2018 }

See the code and how the continue statement is used:

using System;
class for_loop_demo_leap
{
    static void Main()
    {
        int[] arr_years = { 1992, 1994, 1996, 2000, 2002, 2008, 2010, 2012, 2016, 2018 };

        Console.WriteLine("Following are the leap years in the Array:\n");

        for (int l = 0; l < arr_years.Length; l++)
        {
            if (arr_years[l] % 4 == 0)
            {
                Console.WriteLine(arr_years[l]);
                continue;
            }
        }
        Console.ReadLine();
    }
}

The leap years list:

Following are the leap years in the Array:
1992
1996
2000
2008
2012
2016

You can see that other years are filtered as those encountered the continue statement in the for loop.

Note: Leap year has two other conditions:

  • (i) Year is not divisible by 100. For example, 1900 is not a leap year, although it can be divided by 4.
  • (ii)Year can be divided by 400 is a leap year. For example, 2000 is a leap year as it can be divided by 400 (though it can be divided by 100 as well).
  • (iii)You need to incorporate these two conditions as well in the above code by using if..else if ladder, etc.

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!