Loops in C#: For, While, and Do-While Explained
Loops are essential for repeating code execution in C#. This guide will cover the use of for, while, and do-while loops, along with sample code to help you understand how they work.
For Loop
The for loop is used to execute a block of code a specified number of times. It has the following syntax:
for (initialization; condition; increment)
{
// Code to execute in each iteration
}
Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration " + i);
}
While Loop
The while loop is used to execute a block of code as long as a condition is true. It has the following syntax:
while (condition)
{
// Code to execute as long as the condition is true
}
Example:
int count = 0;
while (count < 5)
{
Console.WriteLine("Count is " + count);
count++;
}
Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once. It has the following syntax:
do
{
// Code to execute
} while (condition);
Example:
int n = 5;
do
{
Console.WriteLine("n is " + n);
n--;
} while (n > 0);
Conclusion
Loops are powerful tools for automating repetitive tasks in C#. You've learned about for, while, and do-while loops, along with their syntax and usage.
Practice using these loops in your C# programs to efficiently iterate through data and perform tasks repeatedly. Loops are a fundamental part of programming and can greatly enhance the functionality of your applications.