C# For Loop
Introduction
The for
loop is one of the most commonly used control flow statements in C#. It allows you to execute a block of code repeatedly for a specific number of times. For loops are particularly useful when you know in advance how many times you want to iterate through a block of code.
In this tutorial, you'll learn:
- The syntax and structure of the C# for loop
- How to create and use for loops
- Common patterns and techniques
- Real-world applications
Basic Syntax
The syntax of a for loop in C# consists of three main parts:
for (initialization; condition; iteration)
{
// Code to be executed
}
Let's examine each part:
- Initialization: Executes once at the beginning of the loop. Typically used to declare and initialize a counter variable.
- Condition: Evaluated before each iteration. If true, the loop continues; if false, the loop ends.
- Iteration: Executes after each iteration. Usually increments or decrements the counter.
Basic For Loop Example
Here's a simple example that counts from 1 to 5:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example:
int i = 1
initializes a counter variablei
with the value 1i <= 5
specifies that the loop should continue as long asi
is less than or equal to 5i++
increments the counter by 1 after each iteration
Variations of For Loops
Counting Backwards
You can count backwards by decrementing the counter:
for (int i = 10; i > 0; i--)
{
Console.WriteLine($"Countdown: {i}");
}
Console.WriteLine("Blast off!");
Output:
Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
Custom Increments
You're not limited to incrementing by 1. You can use any increment you want:
// Count by 2s (even numbers)
for (int i = 0; i <= 10; i += 2)
{
Console.WriteLine($"Even number: {i}");
}
Output:
Even number: 0
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
Multiple Variables
You can use multiple variables in a for loop:
for (int i = 1, j = 10; i <= 5; i++, j--)
{
Console.WriteLine($"i = {i}, j = {j}");
}
Output:
i = 1, j = 10
i = 2, j = 9
i = 3, j = 8
i = 4, j = 7
i = 5, j = 6
Advanced For Loop Techniques
Nested For Loops
You can place a for loop inside another for loop, creating nested loops:
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.WriteLine($"i = {i}, j = {j}");
}
Console.WriteLine("----------");
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
----------
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
----------
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
----------
Break and Continue Statements
You can control the flow within a for loop using break
and continue
statements:
break
: Exits the loop immediatelycontinue
: Skips the current iteration and moves to the next one
for (int i = 1; i <= 10; i++)
{
if (i == 3)
{
Console.WriteLine("Skipping 3...");
continue; // Skip the rest of this iteration
}
if (i == 8)
{
Console.WriteLine("Found 8! Breaking the loop.");
break; // Exit the loop
}
Console.WriteLine($"Number: {i}");
}
Output:
Number: 1
Number: 2
Skipping 3...
Number: 4
Number: 5
Number: 6
Number: 7
Found 8! Breaking the loop.
Empty Parts in For Loop
Any part of the for loop can be omitted if needed:
// Initialize outside the loop
int i = 1;
for (; i <= 5; i++)
{
Console.WriteLine(i);
}
// Omitting the increment (handle inside the loop)
for (int j = 1; j <= 5;)
{
Console.WriteLine(j);
j++;
}
// Creating an infinite loop with break condition
for (;;)
{
Console.WriteLine("This is an infinite loop!");
break; // Without this, the loop would run forever
}
Real-World Applications
Iterating Through Arrays
One of the most common uses of for loops is to iterate through arrays:
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine($"Fruit at index {i}: {fruits[i]}");
}
Output:
Fruit at index 0: Apple
Fruit at index 1: Banana
Fruit at index 2: Cherry
Fruit at index 3: Date
Fruit at index 4: Elderberry
Building String Patterns
For loops are great for building patterns:
// Create a simple triangle pattern
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Output:
*
**
***
****
*****
Calculating Values
For loops are useful for calculations like factorial:
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
Console.WriteLine($"Factorial of {number} is {factorial}");
Output:
Factorial of 5 is 120
For Loop vs. Other Loops
It's worth noting when a for loop is most appropriate compared to other loop types:
- For loop: Best when you know the exact number of iterations in advance.
- While loop: Better when you don't know how many iterations you'll need.
- Foreach loop: Ideal for iterating through collections without needing the index.
Common Pitfalls
Off-by-One Errors
Be careful when setting your loop conditions to avoid off-by-one errors:
// If we want to go from 0 to 9 (10 numbers):
for (int i = 0; i <= 9; i++) { } // Correct
for (int i = 0; i < 10; i++) { } // Also correct
for (int i = 0; i <= 10; i++) { } // Incorrect - goes to 10 (11 numbers)
Infinite Loops
Always ensure your loop condition will eventually become false:
// Infinite loop (i never decreases)
for (int i = 10; i > 0; i++)
{
// This will run forever!
}
Summary
The C# for loop is a powerful and flexible control flow statement that allows you to execute a block of code a specific number of times. It consists of initialization, condition, and iteration expressions, which give you fine-grained control over how your loop behaves.
For loops are especially useful when:
- You know exactly how many iterations you need
- You need to track an index while iterating
- You need precise control over the iteration behavior
Throughout this tutorial, we've seen how to create basic for loops, use variations and advanced techniques, and apply them to real-world programming problems.
Exercises
To solidify your understanding, try these exercises:
- Write a for loop that displays all even numbers between 20 and 40.
- Create a program that uses a for loop to calculate the sum of all numbers from 1 to 100.
- Write a nested for loop to create a multiplication table for numbers 1 through 10.
- Implement a for loop that finds and displays all factors of a given number.
- Create a program that uses a for loop to reverse a string.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)