The 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.
In this tutorial, you’ll:
- Learn about the for loop, It’s syntax and execution order used for definite iteration (number of repetitions specified in advance)
- You will cover different variations of for loop.
- Jumping out of a loop or loop iteration prematurely
- See how to stop the current iteration and start the next iteration without breaking out of the loop.
- Then you will explore infinite and nested loops
- Finally, you will learn the use of for loop with array and list.
When you’re finished, you should have a good understanding of how to use definite iteration in C#.
Once you’ve read this article, I’d recommend you to check out my free C# Quick Start Guide Here, where I explained most of the topics in detail with YOUTUBE videos. Read this article Here.
Edit, and test all the CODE examples used in this article with C# online editor: Code Playground
Syntax
The structure of a C# for loop is as follows:
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.
- Initializer: The first part declares and initializes the counter variable. It happens only once before the loop begins.
- 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.
- 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.
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. Initialization is the first action performed by the loop only once, no matter how many times the loop statements are executed. After that is the termination expression, this is some 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.
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. In the end, increments/decrements the iterator each time through the loop after the body statement executes.
The condition is rechecked. 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.
Example: C# for Loop
Here is an example of a simple for loop that displays numbers 1 through 5 in the console window:
Curly braces are optional if the body of the loop contains only one statement.
for (int i = 1; i <= 5; i++)
Console.WriteLine(i);
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:
- The initialization expression
int i = 1
is executed, which declares the integer variablei
and initializes it to 1. - 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. - The statement
Console.WriteLine(i);
is executed. - The update expression
i++
is executed, which increases the counter variable valuei
by 1. - Back to Step 2.
- 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);
}
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
Variations of for Loop
C# for loop has several variations; some may seem awkward 😉. I 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}");
}
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}");
}
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);
}
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++);
}
Note: The third part of the for loop runs after testing the first two parts.
Two semicolons are mandatory and must be used as placeholders to separate the three parts.
int i = 0;
for (; i <= 3;)
{
Console.WriteLine(i++);
}
The break Keyword With for Loop
What if you want to jump out of a loop in the middle, before a for loop condition becomes false?
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.
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 values 4 and 5.
OUTPUT
1
2
3
After break start here.
The continue Keyword With for Loop
What if you want to stop executing the current iteration of the loop and skip ahead to the next iteration?
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.
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 with the next cycle through the loop.
OUTPUT
1
2
3
5
Infinite for Loop
Whenever you don’t give a condition to the for loop, it automatically becomes an infinite for loop, meaning the loop block executes endlessly. Use the double semicolon (;;
) in for loop to make it run infinite times.
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.
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 👍.
Nested for Loops
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.
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.
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:
Difference Between for Loop and while Loop
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 loop elements in one convenient place.
Array with for Loop
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:
The first statement declares a string array called fruitsArray
which contains a list of fruits. You use the 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.
OUTPUT
Apple
Banana
Mango
Orange
List With for Loop
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:
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.
OUTPUT
Apple
Banana
Mango
Orange
Please Share This Post With Love ❤️
Top comments (0)