C# Looping
For Loop
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Example: For Loop
|
|
Explanation
- Initialization:
int i = 0
sets the starting point of the loop. - Condition:
i < 5
determines how long the loop will run. - Iteration:
i++
updates the loop counter after each iteration.
Output
While Loop
The while
loop executes a block of code as long as a specified condition is true. It is useful when the number of iterations is not known in advance.
Example: While Loop
|
|
Explanation
- Condition:
count < 5
is checked before each iteration. - Body:
Console.WriteLine(count)
andcount++
are executed as long as the condition is true.
Output
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.
Example: Do-While Loop
|
|
Explanation
- Body:
Console.WriteLine(value)
andvalue++
are executed first. - Condition:
value < 0
is checked after the loop body is executed.
Output
Foreach Loop
The foreach
loop iterates over a collection or array ( We will talk about array in next chapter). It is useful when you want to iterate over each element without worrying about the index.
Example: Foreach Loop
|
|
Explanation
- Collection:
int[] numbers = { 1, 2, 3, 4, 5 }
is the array to iterate over. - Body:
Console.WriteLine(number)
is executed for each element in the array.