Loops are very common when you are programming. They are used to iterate through a list or array or run until a certain condition has been reached. There are different kinds of loops and this time I want to show you all about the for loop with C#.
Things you should know
For this tutorial you need to know or have the following terms/techniques:
- General C# and .NET knowledge
I am using .NET 6 for this tutorial. - Visual Studio 2022 or higher
Table Of Contents
What is the for loop?
The for loop is a loop that continues executing code until a certain condition has been met. In the case of the for loop, you know exactly how many times the code inside the body of the loop is executed. You use the for loop when you have a list or an array and you want to iterate through that the same number of times as the size of that list or array.
A for loop always looks the same:
The for loop always starts with for and has three statements:
- Statement 1 specifies the initializer and can be used to get a specific item from the list or array.
- Statement 2 defines the condition on how many times the for loop should run.
- Statement 3 is always executed after the body is done.
Examples
Below are some examples that show how the for loop with C# works.
Basic example
In the for loop, I first specify the initializer, which is an int. Then I define how many times the for loop should execute the code block between the curly brackets (5 times, because movieTitles.Count equals 5). And lastly, I tell the loop to add 1 to i every time the code block has been executed. This way i will become equal to movieTitles.Count and not smaller than that count, thus the for loop is done.
In other words: The for loop will keep executing the code block as long as i is smaller than movieTitles.Count.
Stopping / Break
In some cases, you might want to stop or abort the for loop before the condition is met. You can do this with a break. In the example below, the while loop will stop as soon as i equals 5.
Next iteration / Continue
In some cases, you want to skip some of the code and continue to the next run/iteration. This can be achieved by using the continue. In the example below, the number 5 won’t be printed on the console.
