The for loop in C# is used when you know in advance how many times you want to execute a statement or a block of statements. It is a powerful and flexible loop that allows you to repeat a task a set number of times, or even until a certain condition is met.
The basic syntax for a for loop is:
for (initialization; condition; increment/decrement)
{
// Code to be executed
}
• Initialization: This step is executed first and only once. It typically initializes the loop counter.
• Condition: The loop runs as long as this condition is true.
• Increment/Decrement: This step is executed after each iteration. It typically updates the loop counter.
1. Basic for Loop Example
The simplest example of a for loop is iterating through a range of numbers and performing some action for each iteration.
Example:
using System;
class Program
{
static void Main()
{
// A basic for loop that prints numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4
5
In this example:
• The loop starts with i = 1 and continues until i <= 5.
• After each iteration, i is incremented by 1 (i++).
2. for Loop with Decrementing Counter
You can also use a for loop to iterate backwards by decrementing the loop variable.
Example:
using System;
class Program
{
static void Main()
{
// A for loop that prints numbers from 5 to 1
for (int i = 5; i >= 1; i--)
{
Console.WriteLine(i);
}
}
}
Output:
5
4
3
2
1
In this case:
• The loop starts at i = 5 and decrements the value of i after each iteration until i reaches 1.
3. Using a for Loop to Iterate Through an Array
A very common use case of the for loop is iterating over arrays. This allows you to perform an operation on each element of the array.
Example:
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
// A for loop to iterate through the array
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
In this example:
• The loop iterates from i = 0 to i < numbers.Length, ensuring that each element in the array is accessed.
• numbers[i] gives the value of the element at the current index i.
4. Nested for Loops
You can also nest for loops inside one another. This is useful for working with multidimensional data structures like matrices or performing more complex iterations.
Example:
using System;
class Program
{
static void Main()
{
// A 2D array (matrix)
int[,] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
// Nested for loop to iterate through the 2D array
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
In this example:
• The outer for loop iterates through each row of the 2D array.
• The inner for loop iterates through each column of the current row.
• matrix[i, j] accesses the element at row i and column j.
5. Infinite for Loop (with break)
A for loop can be made to run infinitely by setting the condition to true. This is often used for waiting for some external event or input. You can use the break statement to exit the loop.
Example:
using System;
class Program
{
static void Main()
{
// Infinite for loop
for (int i = 0; ; i++) // The condition is always true
{
Console.WriteLine(i);
if (i == 5)
{
break; // Exit the loop when i equals 5
}
}
}
}
Output:
0
1
2
3
4
5
In this example:
• The loop continues indefinitely because the condition is left blank (which means it’s always true).
• The break statement stops the loop once i reaches 5.
6. for Loop with continue Statement
You can use the continue statement inside a for loop to skip the current iteration and continue with the next one.
Example:
using System;
class Program
{
static void Main()
{
// A for loop that skips even numbers
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip the even numbers
}
Console.WriteLine(i);
}
}
}
Output:
1
3
5
7
9
In this case:
• The continue statement causes the loop to skip the current iteration when the number is even and move on to the next one.
7. Best Practices for Using for Loops
• Avoid Infinite Loops: Ensure that the loop has a valid termination condition. Infinite loops should only be used when needed, and you should always have a way to exit them (e.g., break or return).
• Limit Nested Loops: Too many nested loops can reduce code readability and performance. Try to simplify the logic if possible.
• Use foreach for Collections: If you are iterating over collections like arrays, lists, or dictionaries, consider using a foreach loop as it’s more readable and easier to maintain.