loops in C# full Explanation
In C#, there are several types of loops available,
but the most commonly used loop is the `for` loop. However, I will explain the Different
types of loops in C# along with their full explanations:
1.
for Loop:
v The
`for` loop is used when you know the number of iterations in advance.
v It
consists of three parts: initialization, condition, and iteration expression.
v The
loop executes as long as the condition is true.
v Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
- Output:
0
1
2
3
4
2.
while Loop:
v The
`while` loop is used when you want to execute a block of code repeatedly until
a condition becomes false.
v It
checks the condition before each iteration.
v Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
- Output:
0
1
2
3
4
3.
do-while Loop:
v The
`do-while` loop is similar to the `while` loop, but it checks the condition
after each iteration.
v It
executes the code block at least once before checking the condition.
v Example:
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
- Output:
0
1
2
3
4
4.
foreach Loop:
v The
`foreach` loop is used to iterate over elements in a collection such as arrays,
lists, or other enumerable types.
v It
automatically retrieves each element of the collection without the need for an
index.
v Example
with an array:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
- Output:
1
2
3
4
5
These are the Different types of loops available in
C#. Each loop has its own purpose and usage scenarios. The choice of loop
depends on the specific requirements of your program, such as knowing the
number of iterations, condition-based execution, or iterating over collections.
0 Comments