C# for Loop

C# for loop is very common in programming. This loop is ideal for performing a fixed number of iterations when the programmer needs to iterate over a block of code a specific number of times. C# for loop uses in-built syntax for initializing, incrementing, and testing the value of a counter variable that determines how many times the loop will execute.

C# for Loop Syntax

C# for Loop Syntax

You begin C# for loop syntax with the for keyword followed by a set of parentheses. Within the parentheses are three different parts separated by two semicolons. These parts control the looping mechanism. Let’s examine each.

  1. Initializer: The first part declares and initializes the counter variable. It happens only once before the loop begins.
  2. Condition: The second part is the Boolean expression that determines when the loop stops. If the expression returns true, the code within the loop’s body executes. Otherwise, the loop stops. 
  3. Iterator: The third part is something that uses a C# unary operator. This piece of code increments/decrements the counter variable initialized in the first part of the C# for statement and is executed at the end of each iteration.

Note: C# unary operator provides increment (++) and decrement () operator.

C# for Loop Execution Order

The first part is the initialization expression, which normally allows you to set up an iterator (also known as “loop variable”) to its starting value. This is the first action performed by the loop only once, no matter how many times the statements within the loop are executed. After that is the termination expression. This is some sort of boolean condition to inform the loop when to stop. As long as this expression is true, the body of the loop will repeat. The loop’s body is surrounded by the braces immediately following the for statement. Finally, at the end is the update expression that increments/decrements an iterator variable. This statement takes effect at the bottom of the loop, just before the condition is checked.

C# for Loop Flowchart

C# for Loop Flowchart

The semantic of C# for loop is slightly more complicated than while and do-while loops: Initialization occurs only once before the loop begins, and then the condition is tested, which evaluates to true or false. If the condition is true, the code inside the loop’s body executes. At the end, increments/decrements the iterator each time through the loop after the body statement executes.

The condition is checked again. If the condition is still true, the whole process starts over again. This logic repeats until the condition becomes false. In that case, C# exits the for loop and the next first statement after the loop continues.

C# for Loop Example

Here is an example of a simple for loop that displays numbers 1 through 5 in the console window:

C# for Loop Example

Curly braces are optional if the body of the loop contains only one statement.

for (int i = 1; i <= 5; i++)
    Console.WriteLine(i);

Test Code

A semicolon (;) separates the three parts. The initialization part is int i = 1, the test part is i <= 5, and the increment part is i + + which uses an increment operator (++). That means the value of i will go from 1 to 5. Within the body of the loop is a single statement, which is the call to Console.WriteLine method to print out the value of i variable in the console window.

This is what happens when above for loop executes:

  1. The initialization expression int i = 1 is executed. This declares the integer variable i and initializes it to 1. 
  2. The expression i <= 5 is tested to return true or false. If the expression is true, continue with Step 3. Otherwise, the loop is finished. 
  3. The statement Console.WriteLine(i); is executed. 
  4. The update expression i++ is executed. This increases the counter variable value i by 1. 
  5. Back to Step 2.
  6. Steps 2–4 are repeated as long as the condition is true.

If you run the above example, the output looks like this:

OUTPUT

1
2
3
4
5

You can alternatively decrement the counter variable. Look at the following code:

for (int i = 5; i >= 1; i--)
{
    Console.WriteLine(i);
}

Test Code

I have initialized i variable with the value 5. The loop iterates as long as i is greater than or equal to 1. At the end of each iteration, i is decremented by 1. It will display numbers going down from 5 to 1.

OUTPUT

5
4
3
2
1

C# for Loop Variations

C# for loop has several variations, some may seem awkward 😉. I just want to show you alternatives, otherwise rearranging the parts of a for statement like this is discouraged.

C# for loop with two variables: You can split first and third parts into several statements using the comma operator (,). Here is an example in which I have used multiple initialization statements and multiple iterator statements all at the same time. There are two counters, counter i++ moves up from 1 and the counter j– moves down from 100:

for (int i = 1, j = 100; i <= 3; i++, j--)
{
    Console.WriteLine($"i-{i}, j-{j}");
}

Test Code

You can perform multiple tests using compound conditions.

for (int i = 1, j = 100; i <= 3 && j >= 98; i++, j--)
{
    Console.WriteLine($"i-{i}, j-{j}");
}

Test Code

OUTPUT

i-1, j-100
i-2, j-99
i-3, j-98

Another option is to leave out one or more parts from the for statement. Let’s leave out the initialization part if an int value has been declared before the loop.

int i = 0;
for (; i <= 3; i++)
{
    Console.WriteLine(i);
}

Test Code

You can move around the third part of the for statement, which is i++. Let’s move the last part in the loop’s body.

for (int i = 0; i <= 3;)
{
    Console.WriteLine(i++);
}

Test Code

Note: The third part of the for loop runs after the first two parts are tested. 

Two semicolons are mandatory and must be used as placeholders to separate the three parts.

int i = 0;
for (; i <= 3;)
{
    Console.WriteLine(i++);
}

Test Code

C# for Loop Break

What if you want to jump out of a loop in the middle, before a for loop condition becomes false?

C# for Loop Break

The break keyword does that. C# break operator causes the for loop to stop immediately before it completes the current iteration and passes control to the first statement immediately after the loop. With a break statement, you’re stopping only the block of code the break is in.

C# for Loop Break

Test Code

When the counter reaches 4, the condition (i == 4) tests to true. The break keyword doesn’t just skip the rest of the iteration 4; it stops altogether and resumes execution immediately following the loop. Loop skipped the value 4 and 5.

OUTPUT

1
2
3
After break start here.

C# for Loop Continue

What if you want to stop executing the current iteration of the loop and skip ahead to the next iteration?

C# for Loop Continue

You can do this with the continue keyword. C# continue operator stops the current iteration, without breaking out of the loop entirely, it just jumps ahead to the next iteration of the loop. The continue statement passes control straight to the for statement to start over. Let’s look at this more closely with an example.

C# for Loop Continue

Test Code

In the above code example, the loop prints out all the numbers except one. It skips 4 due to the continue statement. When the loop hits condition (i == 4), it immediately skips Console.WriteLine(i) and goes directly to the for statement to check the condition. If the condition is still true, the loop then continues on with the next cycle through the loop.

OUTPUT

1
2
3
5

Infinite for Loop in C#

All three parts of the for statement are optional, except two semicolons for(;;). If the missing part is a condition, C# assumes no condition as a ‘true’ condition, thus creating an infinite or endless loop. Let’s look at the following infinite for loop example with the double semicolon.

C# infinite for loop

for (; ; )
{
    Console.WriteLine("I am infinite for loop");
}

Note: To stop an endless loop, press CTRL + C on the keyboard. I mean you press and hold down the CTRL key, and while holding it down, press the C key.

You can use the following code to see how an infinite for loop can be stopped with a break statement.The counter increments while you are trapped in the endless loop. Once the counter is greater than or equal to 4, you break out of the for loop with the break keyword 👍.

Infinite for Loop in C# with Break

Test Code

Nested for Loop in C#

A loop placed within another loop’s body is a nested loop. The outer loop must completely contain the inner loop. In the following image, the outer for loop entirely contains the inner for loop within its body. With each iteration of the outer loop triggers the inner loop which executes multiple times until the condition becomes false.

Nested for Loop in C#

In the following code example, there are two for loops, one within the other. The outer for loop will use int i = 1 and the inner for loop will use int j = 0 as their initialization statements. To control the loop iterations, I have declared and initialized integer variable numberOfTimes. If you set the numberOfTimes to 2, then each for loop will iterate 2 times.

C# Nested for Loop

Test Code

In the following example, the break statement exits inner for loop and returns control to the outer for loop, rather than breaking out of all the loops entirely. To exit both loops simultaneously, you must use two separate break keywords, one for each loop:

C# Nested for Loop with Break

Test Code

C# for vs while Loop

C# for vs while Syntax

To write a while loop, you initialize an iterator variable, and as long as its condition is true, you continue to execute the body of the while loop. To avoid an infinite loop, the body of the while loop must update the iterator variable. This loop requires more external variables to control. 

Unlike the while loop that relies on an external variable, the for loop contains all the elements of the loop in one convenient place.

C# for vs while Example

Test Code

C# for Loop Array

You can use a for loop when you need to loop through an array until a specific condition is reached (for example, end of an array). Here’s an example that shows how you can iterate through the items of an array using C# for loop:

C# for Loop Array

The first statement declares a string array called fruitsArray which contains a list of fruits. You use Length property of the fruits array to determine how many items an array contains, which is needed for the loop iterations. To access the array items individually, you need to use the value of i as an indexer inside the square brackets like this fruitsArray[i]. The value of i will go from 0 to 3. Finally, as you loop over each item in the array, its value is printed to the console window.

Test Code

OUTPUT

Apple
Banana
Mango
Orange

C# for Loop List

You can use a for loop when you need to loop through a list until it reaches a termination condition (for example, end of a list). Following example shows how you can iterate all the items of a list using C# for loop:

C# for Loop List

The first statement declares a list named fruitsList that contains 4 fruits. You need Count property to find out the total number of fruits in the list, which is needed for the loop iterations. To access the list items individually, you need to use the value of i as an indexer inside the square brackets like this fruitsList[i]. The value of i will go from 0 to 3. As you loop over each item in the list, its value is printed to the console window.

Test Code

OUTPUT

Apple
Banana
Mango
Orange

Community Input

💬 What other C# for loop topics should I cover here?

Please use twitter or instagram to share your suggestions. We will add your feedback here.

Share With Love ❤️

Like this on Instagram

Like this on twitter

Resources

  1. C# unary operator
  2. Increment operator ++
  3. Decrement operator —
  4. Break
  5. continue
  6. Array
  7. List
Sending
User Rating 5 (1 vote)

TidBits