Loops

 Loops:

In C#, loops are control flow structures that allow you to repeatedly execute a block of code based on a specified condition.


Types

1.for

2.foreach

3.while

4.do-while


1.for:

The for loop is used when you know the number of iterations in advance.


Syntax:

for (initialization; condition; iteration)

{

    // code to be repeated

}


Example:

for (int i = 0; i < 5; i++)

{

    Console.WriteLine(i);

}


2.foreach:

The foreach loop is used to iterate over elements in an array or other enumerable collections.


Syntax:

foreach (var item in collection)

{

    // code to be repeated

}


Example:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (var number in numbers)

{

    Console.WriteLine(number);

}


3.while:

The while loop is used when the number of iterations is not known in advance, and the loop continues as long as a specified condition is true.


Syntax:

while (condition)

{

    // code to be repeated

}


Example:

int i = 0;

while (i < 5)

{

    Console.WriteLine(i);

    i++;

}


4.do-while:

The do-while loop is similar to the while loop, but the condition is checked after the loop body is executed, guaranteeing that the loop runs at least once.


Syntax:

do

{

    // code to be repeated

} while (condition);


Example:

int i = 0;

do

{

    Console.WriteLine(i);

    i++;

} while (i < 5);

Comments