Home C# A for loop in C# tutorial

A for loop in C# tutorial

The for loop in C# is a versatile and commonly used control structure for repeating a block of code a certain number of times. It’s especially useful when the number of iterations is known beforehand.

In this tutorial, we’ll cover:

1. Basic Structure of a for Loop

The for loop consists of three parts: initialization, condition, and increment/decrement, separated by semicolons.

This loop structure provides a way to control the start, end, and step size of the loop.

Syntax:

for (initialization; condition; increment/decrement)
{
    // Code to execute in each iteration
}

Example:

using System;

public class ForLoopExample
{
    public static void Main()
    {
        // Print numbers from 1 to 5
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine("Iteration: " + i);
        }
    }
}

In this example:

  • The loop initializes i to 1.
  • The condition i <= 5 checks if i is less than or equal to 5.
  • The increment i++ increases i by 1 after each iteration.

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

2. Looping with Different Increments

The increment section can be customized to use different steps. You can decrement or change the step size depending on the use case.

Example: Looping with a decrement

using System;

public class ForLoopDecrement
{
    public static void Main()
    {
        // Print numbers from 5 down to 1
        for (int i = 5; i >= 1; i--)
        {
            Console.WriteLine("Countdown: " + i);
        }
    }
}

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

Example: Looping with a step of 2

using System;

public class ForLoopStep
{
    public static void Main()
    {
        // Print even numbers from 2 to 10
        for (int i = 2; i <= 10; i += 2)
        {
            Console.WriteLine("Even number: " + i);
        }
    }
}

Output:

Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

3. Using the for Loop with Arrays

The for loop is often used to iterate over arrays or collections, allowing you to access each element by its index.

Example:

using System;

public class ArrayForLoop
{
    public static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };

        // Loop through the array and print each element
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("Element at index " + i + ": " + numbers[i]);
        }
    }
}

In this example:

  • numbers.Length gives the total number of elements in the array.
  • The loop accesses each element using its index 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

4. Nested for Loops

You can place one for loop inside another, which is called nesting. Nested loops are useful when working with multi-dimensional arrays or performing tasks in a grid-like structure.

Example: Multiplication Table

using System;

public class MultiplicationTable
{
    public static void Main()
    {
        // Generate a multiplication table from 1 to 5
        for (int i = 1; i <= 5; i++)
        {
            for (int j = 1; j <= 5; j++)
            {
                Console.Write((i * j) + "\t");
            }
            Console.WriteLine();
        }
    }
}

In this example:

  • The outer loop iterates over rows.
  • The inner loop iterates over columns for each row, producing a multiplication table from 1 to 5.

Output:

1   2   3   4   5
2   4   6   8   10
3   6   9   12  15
4   8   12  16  20
5   10  15  20  25

5. break and continue Statements in for Loops

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next.

Example: Using break

using System;

public class BreakExample
{
    public static void Main()
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i == 6)
            {
                break; // Exit loop when i equals 6
            }
            Console.WriteLine("Value: " + i);
        }
    }
}

Output:

Value: 1
Value: 2
Value: 3
Value: 4
Value: 5

In this example, the loop stops executing when i reaches 6 due to the break statement.

Example: Using continue

using System;

public class ContinueExample
{
    public static void Main()
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i % 2 != 0)
            {
                continue; // Skip odd numbers
            }
            Console.WriteLine("Even Value: " + i);
        }
    }
}

Output:

Even Value: 2
Even Value: 4
Even Value: 6
Even Value: 8
Even Value: 10

Here, the continue statement skips odd numbers, so only even numbers are printed.

Summary

The for loop in C# is flexible and powerful, especially useful when you know the exact number of iterations required. Here’s a quick recap of the different ways you can use for loops:

  • Basic for Loop: The standard loop structure with an initialization, condition, and increment.
  • Custom Increments/Decrements: Modify the step size to control the loop’s progress.
  • Looping Through Arrays: Iterate through array elements using their indexes.
  • Nested Loops: Perform complex tasks in a grid or matrix structure.
  • Using break and continue: Control the flow within the loop, either by exiting early or skipping certain iterations.

 

You may also like