loop type in c#
In C#, there are several types of loops that you can use to iterate over a set of instructions or a collection of data:
- 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);
}
- 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++;
}
- 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);
- 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.