Loops
Loops in C# are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops in C#: for, while, and do-while.
– For loop:
The for loop in C# is used to iterate over a range of values. The basic syntax of a for loop is as follows:
for (initialization; condition; increment)
{
// code to execute repeatedly
}
Here, initialization is the statement used to initialize the loop counter variable, condition is the condition that must be true to continue looping, and increment is the statement used to update the loop counter variable at the end of each iteration.
Here’s an example of using a for loop in C# to print the numbers 1 through 10:
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
– While loop:
The while loop in C# is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while loop is as follows:
while (condition)
{
// code to execute repeatedly
}
Here, condition is the condition that must be true to continue looping.
Here’s an example of using a while loop in C# to print the numbers 1 through 10:
int i = 1;
while (i <= 10)
{
Console.WriteLine(i);
i++;
}
– Do-while loop:
The do-while loop in C# is similar to the while loop, but the code inside the loop is executed at least once, even if the condition is false. The basic syntax of a do-while loop is as follows:
do
{
// code to execute repeatedly
} while (condition);
Here, condition is the condition that must be true to continue looping.
Here’s an example of using a do-while loop in C# to print the numbers 1 through 10:
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 10); Loops are a powerful tool in C# for executing a block of code repeatedly until a certain condition is met. By using loops, you can write programs that can handle a wide range of tasks, from simple tasks like printing numbers to complex tasks like searching through large amounts of data.
Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops. You choose the type of loop based on the type of task you need to perform
- You can loop a set number of times with a for loop.
- You can loop through all the items in a collection of data using a foreach loop.
- You can loop while a certain condition holds true, using a while loop.
The for and foreach loops are ideal for sets of data that have known, fixed sizes. The while loop is a more flexible construct that allows you to continue processing until a condition is met. The while loop is often used with repetitive tasks or calculations that don’t have a set number of iterations.
Apply for ASP.NET Certification Now!!
https://www.vskills.in/certification/certified-aspnet-programmer