Loops in C#
Introduction to Loops
Loops are control structures used to repeat a block of code multiple times. They are essential for tasks that require repeated execution, such as iterating over arrays or collections. In C#, there are several types of loops: for, while, do-while, and foreach.
The for
Loop
The for
loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and iteration statement.
for (int i = 0; i < 5; i++) { Console.WriteLine("Iteration: " + i); }
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The while
Loop
The while
loop continues to execute as long as its condition remains true. It's useful when the number of iterations is not known.
int i = 0; while (i < 5) { Console.WriteLine("Iteration: " + i); i++; }
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the loop body is executed at least once.
int i = 0; do { Console.WriteLine("Iteration: " + i); i++; } while (i < 5);
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
The foreach
Loop
The foreach
loop is used to iterate over a collection or an array. It simplifies the code by eliminating the need for an index variable.
int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int number in numbers) { Console.WriteLine("Number: " + number); }
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Nested Loops
Loops can be nested within other loops. This is useful for multi-dimensional arrays or when performing operations on a grid.
for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Console.WriteLine("i: " + i + ", j: " + j); } }
Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
Breaking Out of Loops
The break
statement is used to exit a loop prematurely. This can be useful when a certain condition is met and further iterations are unnecessary.
for (int i = 0; i < 10; i++) { if(i == 5) { break; } Console.WriteLine("Iteration: " + i); }
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Continuing to the Next Iteration
The continue
statement skips the current iteration and proceeds to the next iteration of the loop.
for (int i = 0; i < 10; i++) { if(i % 2 == 0) { continue; } Console.WriteLine("Odd number: " + i); }
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9