Table of contents >> Introduction > For loop
High importance article

The for loop is a kind of repeating code construct which is a bit more complex than the previous types of loops we learned so far. On the other hand, they can solve more complicated tasks, with less code involved.

The syntax of the for instruction is the following:

1
2
for (start_value; end_condition; increment_value)
    instructions;

When the program repeats (cycles) the instructions for a certain number of times, you will usually use a variable called control variable, which indicates how many times you executed the instructions. So, the for loop contains four sections. start_value section initializes our control variable with a default value, which most of the times is 0. The next section, end_condition usually tests the control variable value to see if the instructions were ran the desired number of times. increment_value section usually increments or decrements our control variable by 1 (depending on the behavior we are expecting) or any other value we want, each time the loop runs the instructions. Finally, the fourth section of the for loop are the loop block, in which we place the instruction or the instructions we want to be executed whenever the loop cycles.

Lets take the simplest example for demonstrating the usage of the for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int counter = 0; counter < 10; counter++)
            {
                Console.WriteLine(counter);
            }
            
            Console.WriteLine(counter);
        }
    }
}

The output on the console will be:

0
1
2
3
4
5
6
7
8
9
 

In our example, we declared an integer variable (our control variable) called counter and initialized it to the default value of 0. Next, we specified that we want the loop to be executed only if our counter variable’s value is less than 10. Finally, we instructed it to increment our counter variable by 1 on each cycle of the loop.

So, we initialized a variable called counter to the value 0. The for loop executed the instructions inside the loop block and increments the value of counter by 1. After that, it checks the condition: is counter less than 10? If yes, run the instructions again, increment the variable again, perform the check of the value again, etc, until the check of our counter variable’s value determines that it’s value was incremented to 10, which will return false when we check if our variable is less than 10.

As I said before, it is not imperative that we increment our variable. we can also decrement it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int counter = 9; counter >= 0; counter--)
            {
                Console.WriteLine(counter);
            }
            
            Console.WriteLine(counter);
        }
    }
}

Which will display:

9
8
7
6
5
4
3
2
1
0
 

In this case, the loop will perform the same way as in our previous case, with three differences: first, we initialized our variable as 9, not 0; second, we specified the ending condition of our loop to be when our counter variable is greater than or equal to 0; third, we instructed our variable to decrement by 1 each loop. Basically, the program will now count down from 9 to 0.

We could also specify a different increment factor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int counter = 0; counter < 100; counter += 10)
            {
                Console.WriteLine(counter);
            }
            
            Console.WriteLine(counter);
        }
    }
}

You can already figure it out. We told our program to increment our control variable by 10 on each cycle, until the value gets equal or greater than 100:

0
10
20
30
40
50
60
70
80
90
 

We can also use any other mathematical operation, for instance multiplication:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int counter = 2; counter < 1025; counter *= 2)
            {
                Console.WriteLine(counter);
            }
            
            Console.WriteLine(counter);
        }
    }
}

which will make us count in multiplication steps by 2:

2
4
8
16
32
64
128
256
512
1024
 

You should also understand the scope of our control variable (which sections of the code is it visible and accessible). Following example will demonstrate this aspect:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int num = 0; num < 10; num++)
            {
                // The variable num is visible here and it can be used
            }
            
            // Here num can not be used
        }
    }
}

So, when we declare our control variable in our for loop, it is only visible inside that loop. Happily, we can use an external variable, and simply omit to declare one in our loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 0;
            
            for (; num < 10; num++)
            {
                // The variable num is visible here and it can be used
            }
            
            // The variable num is also visible here and it can be used
        }
    }
}

From the above code, you can see that since we declared our num variable outside the for loop, it is visible and accessible from inside and outside our loop. Also you can notice that since we declared it already outside the for loop, we can omit its declaration inside our loop; however, we still need to place the ; character.

The declaration part is not the only thing we can omit in a for loop. For instance, in the following example, we are declaring our control variable outside the loop, and increment it inside the for loop body:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 0;
            
            for (; num < 10; )
            {
                num++;
                Console.WriteLine(num);
            }
            
            Console.ReadLine();
        }
    }
}

Hack, we can even declare a for loop without any parameters, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (;;)
            {
                Console.WriteLine("Iterated!");
            }
            
            Console.ReadLine();
        }
    }
}

In this case, we will get an infinite loop, since there is no condition to end it, and the program will continue to print "Iterated!" until the end of times (or until you close it 😉)

Finally, you can specify multiple variable controls and conditions for a single for loop. For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1, sum = 1; i < 128; i = i * 2, sum += i)
            {
                Console.WriteLine("i={0}, sum={1}", i, sum);
            }
            
            Console.ReadLine();
        }
    }
}

The concepts explained in this lesson are also shown visually as part of the following video: