Skip to main content

Command Palette

Search for a command to run...

loop type in c#

Published
•2 min read•View as Markdown
B
Senior Software Engineer | Backend, Cloud, Data, Machine Learning

In C#, there are several types of loops that you can use to iterate over a set of instructions or a collection of data:

  1. for loop - executes a block of code repeatedly for a fixed number of times, based on a counter or iterator variable.

Syntax:

for (initialization; condition; increment/decrement)
{
    // code to be executed
}

Example:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
  1. while loop - executes a block of code repeatedly as long as a specified condition is true.

Syntax:

while (condition)
{
    // code to be executed
}

Example:

int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    i++;
}
  1. do-while loop - executes a block of code repeatedly as long as a specified condition is true, but it checks the condition after executing the block of code at least once.

Syntax:

do
{
    // code to be executed
}
while (condition);

Example:

int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i < 10);
  1. foreach loop - iterates over all the elements in an array or collection.

Syntax:

foreach (type variableName in collection)
{
    // code to be executed
}

Example:

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

These are the main types of loops in C#, and they can be used to implement different types of iterations based on the specific needs of your program.

More from this blog

yesicbap

437 posts