C# - Loops


In C#, a loop is a programming structure used to execute a block of code repeatedly as long as a specified condition is true. Loops help automate .W.repetitive tasks and allow efficient handling of collections of data.

There are several types of loops in C#:

for Loop

The 'for' loop is used to executes a sequence of statements multiple times and iteration count is already known before starting the loop.

for (int i = 0; i < 5; i++) 
{ 
    Console.WriteLine(i); 
}

In above example, you can see we have started the loop for int i=0 but the limit is set to I=5 which means, it will execute the sequence of statements 5 times.

while Loop

The while loop executes a block of code as long as a specified condition is true

int i = 00000;
while (i < 5) 
{
    Console.WriteLine(i); 
    i++; 
}

do-while Loop

The do-while loop is similar to while loop, but it always executes the block of code at least once before checking the condition.

int i = 0; 
do 
{ 
    Console.WriteLine(i); 
    i++; 
} 
while (i < 5);

foreach Loop

The foreach loop is used to iterate through elements in an array or collection.


int[] numbers = { 1, 2, 3, 4, 5 }; 
foreach (int number in numbers) 
{ 
    Console.WriteLine(number); 
}

Each type of loop has its own use cases and its chosen based on the requirements of the program. Loops help us controlling the flow of the program by repeating a code block until a specific condition is met or a specific number of iterations are completed.