Full Explanation of Loops in C# (for, while, do-while, foreach)
Introduction: Understanding Loops in C#
Loops are a fundamental concept in programming, enabling you to execute a block of code repeatedly based on a specific condition. In C#, there are several types of loops to choose from. The most commonly used loop is the for loop, but understanding all loop types will help you select the right one for any given scenario.
In this blog, we’ll dive into the four main types of loops in C#: for
, while
, do-while
, and foreach
, explaining their syntax and use cases with examples.
1. For Loop
The for loop is ideal when you know the exact number of iterations in advance. It’s structured in three parts: initialization, condition, and iteration expression.
Syntax:
for (initialization; condition; iteration expression)
{
// Code to execute during each iteration
}
Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Output:
0
1
2
3
4
Explanation:
In this example, the for
loop initializes i
to 0 and runs as long as i < 5
. With each iteration, i
increments by 1. The loop stops when i
reaches 5.
2. While Loop
The while loop repeatedly executes a block of code as long as a specified condition evaluates to true. It checks the condition before each iteration.
Syntax:
while (condition)
{
// Code to execute while the condition is true
}
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
Output:
0
1
2
3
4
Explanation:
Here, the while
loop checks if i < 5
. Since it is true, the code inside the loop runs, and i
is incremented after each iteration. The loop stops when i
becomes 5.
3. Do-While Loop
The do-while loop is similar to the while
loop, but with a key difference: it checks the condition after each iteration. This ensures that the code inside the loop executes at least once, even if the condition is false.
Syntax:
do
{
// Code to execute at least once
}
while (condition);
Example:
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
Output:
0
1
2
3
4
Explanation:
In this example
0 Comments