A Quick Introduction to For Loops in C#
What is a For Loop?
A For Loop is a structure that allows us to iterate a block of code a specific number of times. While all loops are used for iterative purposes, the for loop excels at giving us the ability to know exactly how many times the block of code will run.
The Syntax of a For Loop is as follows:
- Initialization: The default or starting index number. This is a variable that can have any name, however, in C# and C++, this value is traditionally express as i( E.g. i = 0;).
- Condition: The condition that specifies how long the Loop will be running. E.g. i < 10 → Which means that as long as the index number is less than 10, it will keep running.
- Update: An incrementation or subtraction to the index variable. As the loop progresses, it will actively compare the new value(the updated) vs the condition value in each iteration. This is repeated until the value reaches the threshold set in the condition.
How to Break Out of Loops Early
Breaking out of a loop early can be useful in a variety of ways. For example, if you are going through a list and want the Loop to stop once it finds a specific value or item on the list, or even if you are programming traditional game logic and an event interrupts the flow of things. Breaking out of a loop early is simple, and you might already be familiar with it from implementing Switch-Statements.
To break out of a loop, you simply need to state a condition followed by a break; statement.
This loop is unique to the C# language, while the concept is the same as a for loop the syntax differs. A foreach loop works exceptionally well at iterating through collections such as arrays.
The Syntax goes as follows:
- var item: The name of the variable that is searched for or that will be iterated.
- in: The keyword that specifies in which collection the variable is searched for.
- itemName: The name of the array or collection.
In the next article, I’ll be taking a look at while loops!