In C#, loops are used to repeatedly execute a block of code. There are three primary types of loops in C#: for
, while
, and do-while
. Let's explore each one with examples.
1. The for
Loop:
The for
loop is often used when the number of iterations is known beforehand.
- The loop initializes
i
to1
. - It continues as long as
i
is less than or equal to5
. - After each iteration,
i
is incremented by1
.
2. The while
Loop:
The while
loop is used when the number of iterations is not known beforehand, and the loop continues as long as a specified condition is true.
- The
count
variable is incremented within the loop.
3. The do-while
Loop:
The do-while
loop is similar to the while
loop, but it always executes the block of code at least once, even if the condition is initially false.
using System;class Program{static void Main(){// Example of a do-while loopint number = 1;do {Console.WriteLine($"Iteration {number}");number++;}while (number <= 5);}}
- The block of code is executed at least once.
- The loop continues as long as
number
is less than or equal to5
.
4. Experiment:
- Try changing the loop conditions and see how it affects the output.
- Combine loops with other control flow statements.
5. Run the Program:
Press F5
or click the "Start Debugging" button to build and run your program. You should see the output with iterations from each loop.