In this post, we will explain the different kinds of loops in C# for beginners.
What're Loops?
- Loops mean repetition, looping back over the same block of code again and again.
- A loop statement allows us to execute a statement or group of statements multiple times.
- Loops can execute a block of code as long as a specified condition is reached.
Loops Type
There are four types of loops in C#:
- While loop: Loops through a block of code as long as a specified condition is True.
- For loop: When you know exactly how many times you want to loop through a block of code.
- Foreach loop: operates on collections of items like arrays or any other built-in list types.
- Do/While loop: Will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
While Loop in C#
- The while loop loops through a block of code as long as a specified condition is True.
The syntax of a while loop in C# is:
while(condition) {
statement(s);
}
For Loop in C#
- You should use the For loop when you know exactly how many times you want to loop through a block of code.
The syntax of For loop in C# is:
for ( init; condition; increment ) {
statement(s);
}
- Init: is executed (one time) before the execution of the code block.
- Condition: defines the condition for executing the code block.
- Increment: is executed (every time) after the code block has been executed.
Foreach loop in C#
- Foreach is a C# loop that operates on collections of items like arrays or any other built-in list types.
- It iterates throw the items of the array or collections.
- It is an alternative to the For loop.
The syntax of Foreach loop in c#
foreach (element in iterable-item)
{
// body of foreach loop
}
In this example, we have used foreach statement to iterate over the array numbers then print its items.
Do / While Loop in C#
- Do/While loop executes the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
The syntax of a do...while loop in C# is:
do
{
// code block to be executed
}
while (condition);
Conclusion
In this post, we have discussed the different types of loop in C# and when we can use it.
See Also