C# - For Loop
C# - The for Loop
Section titled “C# - The for Loop”A for loop is a repetition control structure that allows you to efficiently execute a block of code a specific number of times. It’s the ideal choice when you know in advance how many times you need to iterate, for example, when processing every item in an array.
Syntax of the for Loop
Section titled “Syntax of the for Loop”The for loop syntax consists of three parts, separated by semicolons:
for (initializer; condition; iterator){ // code to be executed in each iteration}initializer: Executed once before the loop starts. This is where you declare and initialize a loop control variable (e.g.,var i = 0).condition: Evaluated before each iteration. If it’strue, the loop body executes. If it’sfalse, the loop terminates.iterator: Executed after each iteration. This is typically used to increment or decrement the loop variable (e.g.,i++).
Control Flow Diagram
Section titled “Control Flow Diagram”The execution flow of a for loop can be visualized as follows:
[ Start ] | v[ 1. Initializer (runs once) ] | v[ 2. Condition Check ] --(is true)--> [ 3. Loop Body Executes ] ^ | | | |(is false) | | | v | `---->[ End Loop ] [ 4. Iterator Executes ] | | `----------------------------------------`Example: A Basic Counter
Section titled “Example: A Basic Counter”This example prints numbers from 1 to 5. Notice the use of var for the loop variable and the more common i++ increment operator.
using System;
Console.WriteLine("Starting countdown...");
for (var i = 1; i <= 5; i++){ Console.WriteLine($"Value of i: {i}");}
Console.WriteLine("...Blast off!");When executed, this code produces:
Starting countdown...Value of i: 1Value of i: 2Value of i: 3Value of i: 4Value of i: 5...Blast off!for vs. foreach
Section titled “for vs. foreach”While a for loop is great for iterating with an index, a foreach loop is often a simpler and safer choice for iterating over collections like arrays and lists when you don’t need the index.
var fruits = new string[] { "Apple", "Banana", "Cherry" };
// Using a 'for' loop (needed if you require the index)Console.WriteLine("\n--- Using for loop ---");for (var i = 0; i < fruits.Length; i++){ Console.WriteLine($"Index {i}: {fruits[i]}");}
// Using a 'foreach' loop (simpler and preferred for simple iteration)Console.WriteLine("\n--- Using foreach loop ---");foreach (var fruit in fruits){ Console.WriteLine(fruit);}Loop Control Statements: break and continue
Section titled “Loop Control Statements: break and continue”You can alter the flow of a loop using control statements:
break: Immediately terminates the loop.continue: Skips the rest of the current iteration and proceeds to the next one.
// Example for 'break' and 'continue'for (int i = 1; i <= 10; i++){ if (i % 2 != 0) { // Skip odd numbers continue; }
if (i > 8) { // Exit the loop if the number is greater than 8 break; }
Console.WriteLine($"Processing even number: {i}");}This will only print Processing even number: 2, 4, 6, and 8.
Common Use Cases
Section titled “Common Use Cases”1. Nested Loops for 2D Data (e.g., Grids, Tables)
Section titled “1. Nested Loops for 2D Data (e.g., Grids, Tables)”Nested for loops are perfect for working with two-dimensional structures, like printing a multiplication table.
for (int i = 1; i <= 5; i++){ for (int j = 1; j <= 5; j++) { // Use padding to align the numbers neatly Console.Write($"{i * j, -4}"); // -4 aligns left with 4 spaces } Console.WriteLine(); // Move to the next line after each row}2. Data Processing and Transformation
Section titled “2. Data Processing and Transformation”Use a for loop to modify elements in an array or list in-place.
var numbers = new int[] { 10, 20, 30, 40, 50 };
// Double each number in the arrayfor (int i = 0; i < numbers.Length; i++){ numbers[i] *= 2;}
Console.WriteLine($"Transformed array: {string.Join(", ", numbers)}");// Output: Transformed array: 20, 40, 60, 80, 100Common Pitfalls
Section titled “Common Pitfalls”- Off-by-One Errors: Be careful with your condition. Using
<=vs.<can be the source of bugs. For a zero-indexed arrayarr, the condition should bei < arr.Length, noti <= arr.Length. - Infinite Loops: Ensure your iterator and condition will eventually lead to the loop’s termination. A condition like
for(int i = 0; i >= 0; i++)will run forever.