for loop

A for loop has three parts.


for(initialization;condition;interation){
   loop body
}

initialization block executes first and it if often used to declare the loop control value.

condition controls the loop body execution. If condition is false, C# starts executing the statement after the for loop.

iteration is executed after each loop iteration. iteration is usually used to update the loop-control variable.

The following code uses the for loop the print the value from 0 to 9.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i);
        }

    }
}

The output:


0
1
2
3
4
5
6
7
8
9

i is the loop-control variable. The scope of i is the for statement. You cannot use i outside.

We can put more variables in the initialization section.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0, prevFib = 1, curFib = 1; i < 20; i++)
        {
            Console.WriteLine(prevFib);
            int newFib = prevFib + curFib;
            prevFib = curFib;
            curFib = newFib;
            Console.WriteLine(curFib);
        }

    }
}

The output:


1
2
1
3
2
5
3
8
5
13
8
21
13
34
21
55
34
89
55
144
89
233
144
377
233
610
377
987
610
1597
987
2584
1597
4181
2584
6765
4181
10946
6765
17711

You can omit any parts of the for loop, the initialization, condition or iteration.

The following example defines the loop-control variable outside for statement.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        for (; i < 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

The output:


0
1
2
3
4
5
6
7
8
9
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.