A loop is a fundamental programming concept that repeats a block of code multiple times. In C#, there are several types of loops:
The for
loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.
for (int i = 0; i < 5; i++) { Console.WriteLine(i); }
This loop will print the numbers from 0 to 4.
The while
loop is used when you want to continue looping as long as a certain condition is true. The condition is checked before each iteration.
int i = 0; while (i < 5) { Console.WriteLine(i); i++; }
This will print numbers from 0 to 4, just like the for
loop.
The do-while
loop is similar to the while
loop, except that the condition is checked after each iteration. This guarantees that the loop will run at least once.
int i = 0; do { Console.WriteLine(i); i++; } while (i < 5);
This will also print numbers from 0 to 4.
Use the slider to set the number of iterations for a for
loop, and see the result below:
Number of iterations: 5
Loop Output:
1. Which loop is best suited when the number of iterations is known beforehand?
2. In which loop does the condition get checked before the loop starts?
3. Which loop guarantees that the loop will run at least once?
4. Which of these is a valid way to increment the variable in a for
loop?
5. What will the following for
loop output?
for (int i = 0; i < 3; i++) { Console.WriteLine(i); }