C# - Loops
C# - Loops
Section titled “C# - Loops”In programming, we often need to repeat an action multiple times. Instead of writing the same code over and over, we use loops. A loop is a control structure that allows you to execute a block of code repeatedly as long as a certain condition is met.
The basic idea of a loop can be visualized as a cycle:
+-------------------------+ | Is the condition true? | +-----------+-------------+ | Yes +---------v---------+ | Execute loop body | +---------+---------+ | +---------v---------+ | Update state | (e.g., increment counter) +---------+---------+ | +-----------+ (Go back and check condition again)
+-----------+-------------+ | No | +-----------v-------------+ | Exit loop | +-------------------------+Types of C# Loops
Section titled “Types of C# Loops”C# provides several types of loops, each suited for different scenarios.
| Loop Type | Best For |
|---|---|
| for loop | When you know the exact number of iterations (e.g., repeat 10 times). |
| foreach loop | Iterating over all elements in a collection (like a list or an array). |
| while loop | When you want to loop as long as a condition is true, and the number of iterations is unknown beforehand. |
| do-while loop | Similar to a while loop, but guarantees the loop body is executed at least once. |
1. The for Loop
Section titled “1. The for Loop”The for loop is ideal for when you need to execute a block of code a specific number of times. It consists of three parts: an initializer, a condition, and an iterator.
using System;
// Print numbers from 1 to 5for (int i = 1; i <= 5; i++){ // i = 1: initializer (runs once at the start) // i <= 5: condition (checked before each iteration) // i++: iterator (runs after each iteration) Console.WriteLine($"Current number: {i}");}Output:
Current number: 1Current number: 2Current number: 3Current number: 4Current number: 52. The foreach Loop
Section titled “2. The foreach Loop”The foreach loop provides a simple, clean way to iterate over the elements of a collection, such as an array, list, or dictionary. It is often the most readable choice for this task.
using System;using System.Collections.Generic;
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
// Loop through each element in the 'fruits' listforeach (var fruit in fruits){ Console.WriteLine($"I like {fruit}s!");}Output:
I like Apples!I like Bananas!I like Cherrys!3. The while Loop
Section titled “3. The while Loop”A while loop repeatedly executes a block of code as long as a given condition is true. The condition is checked before each iteration.
using System;
int countdown = 3;
while (countdown > 0){ Console.WriteLine($"{countdown}..."); countdown--; // It's crucial to change the variable to avoid an infinite loop}
Console.WriteLine("Lift off!");Output:
3...2...1...Lift off!4. The do-while Loop
Section titled “4. The do-while Loop”The do-while loop is similar to the while loop, but the condition is checked after the loop body has executed. This guarantees that the loop will run at least once.
using System;
string? input;do{ Console.WriteLine("Enter 'exit' to quit:"); input = Console.ReadLine(); // ... process input ...} while (input != "exit");
Console.WriteLine("Program terminated.");Loop Control Statements
Section titled “Loop Control Statements”You can change a loop’s normal execution flow using control statements.
break: Immediately terminates the innermost loop and transfers control to the statement following the loop.continue: Skips the rest of the current iteration and proceeds to the next iteration of the loop.
// Example of 'break' and 'continue'for (int i = 1; i <= 10; i++){ if (i % 2 != 0) { continue; // Skip odd numbers }
if (i > 8) { break; // Exit the loop if number is greater than 8 }
Console.WriteLine(i); // This line only runs for even numbers <= 8}Output:
2468Infinite Loops
Section titled “Infinite Loops”An infinite loop occurs when a loop’s condition never becomes false. While sometimes intentional for services that run continuously, they are often a bug. To create an intentional infinite loop, while(true) is more readable than for(;;).
In real-world applications like background services, an infinite loop should be combined with a mechanism for graceful shutdown, such as a CancellationToken, to allow the loop to be stopped safely.