C# for Loop

[print-me]

The C# for loop structure of C# is like an all-in-one looping utility. The for loop acts like the while loop only with some extra features. The syntax of a for loop is quite different compared to the other two looping structures.

for(initialization; condition; operation)
{
   code to repeat;
}

The initialization is where you will initialize your counter variable. That counter is only available or accessible inside the for loop. The condition is where the counter variable will be compared to a value to determine if the for loop should continue it’s looping. The operation handles the modification of the counter variable like incrementing or decrementing it. All of those three are essential for a counter-controlled repetition.

Let’s look an example program that uses the for loop.

using System;

namespace ForLoopDemo
{
    public class Program
    {
        public static void Main()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Number " + i);
            }
        }
    }
}

Example 1 – Using the for Loop

Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10

The program will count from 1 to 10 using the for loop. The for loop header has it all to make the loop. First, it declares a variable that will be used as a counter and then initializes its value to 1. Then it will test the condition provided whether it is less than or equal to 10. Note that the third one which is the operation will not be executed immediately. The code will execute first which prints the current value of i preceded by the string “Number “. Just then will the code i++ be executed which will increment the value of  the counter i by 1 and then the comparison takes place again if the value of i still passes the condition.

If for example you want to reverse the way the program counts, you could write this instead:

for (int i = 10; i > 0; i--)
{
   //code omitted
}

This code will make the program count from 10 to 1 instead of 1 to 10. We initialized the value of the counter to 10 and used the decrement operator () to make the program do a countdown. Some more complex modifications can be done with the condition and the operation part of the for loop. For example, you can use the logical operators to make more complex expressions and you can use different assignment operators for the operation. You can also declare multiple variables that will contribute on the for loop.

for (int i = 1, y = 2; i < 10 && y > 20; i++, y -= 2)
{
   //some code here
}

Note that if you are using two or more counter variables or operations, you must separate them with a comma. The for loop is best used when your loopings continuity is determined by counters. It would be odd to use, but acceptable, to consider for loop in a sentinel-controlled repetition or a repetition where the condition is based on a sentinel that is a value that will make the loop stop. For sentinel-controlled repetition, a while or do while loop is more preferred.

//for version
 
for ( char choice = 'y'; choice != 'n'; )
{
   Console.WriteLine("Repeat?(y/n): ");
   choice = Convert.ToChar(Console.ReadLine());
}
 
//while version
char choice2 = 'y';
 
while(choice2 != 'n')
{
   Console.WriteLine("Repeat?(y/n): ");
   choice2 = Convert.ToChar(Console.ReadLine());
}

Example 2 – Comparing for Loop with while Loop

The operation part of the for loop above was omitted because the continuity of the loop is determined by a user input. It makes the head of the for loop a little odd looking compared to the while loop which looks more natural that’s why I prefer using that when the loop is controlled by a sentinel.