Loops
Explore how to use C# loops such as for, foreach, while, and do...while to repeat code execution while managing conditions. Understand loop control statements break and continue to influence loop behavior and improve program flow.
Loops are constructions that allow us to execute a block of code multiple times until a certain condition is met. We have several types of loops in C#:
The
forloopThe
foreachloopThe
whileloopThe
do...whileloop
The for loop
The syntax of the for loop consists of an initialization, a condition, and an iterator.
for (int i = 0; i < 10; i++){// Body of the loop}
for: The keyword that starts the loop.int i = 0: The initialization statement. It runs once before the loop begins. Here, we create an integer counteriand set it to0.i < 10: The condition. The loop executes as long as this evaluates totrue.i++: The iterator. This executes after every iteration, increasingiby1.
Though we usually prefer integers, the counter does not have to be of the int type; it can be any numeric type.
To sum up, the loop declaration above consists of three statements. Before the first iteration of our for loop, we declare and initialize a counter variable, i. Its value is 0 in the beginning. The loop runs as long as i < 10.
Because i increments by one after each iteration, the loop runs exactly 10 times.
We can check this by ...