Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1k views
in Blog Post by 48 54 93

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#:

  1. While loop: Loops through a block of code as long as a specified condition is True.
  2. For loop: When you know exactly how many times you want to loop through a block of code.
  3. Foreach loop:  operates on collections of items like arrays or any other built-in list types.
  4. 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.

For Loop In C# 


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.

foreach loop in c#


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);

Do While In C#


Conclusion 

In this post, we have discussed the different types of loop in C# and when we can use it.

See Also


1.1k questions

673 answers

454 comments

193k users

تعلم بالعربي PowerApps

تعلم بالعربي Power Automate

If you don’t ask, the answer is always NO!
...