← C# tutorial

C#

Loops

C#'s for loop uses the same three-part structure as Java and C++: initializer, condition, update.

Example: summing with a for loop

using System;

class Program {
    static void Main() {
        int total = 0;
        for (int i = 1; i <= 5; i++) {
            total += i;
        }
        Console.WriteLine($"Total: {total}");
    }
}
Total: 15

C# also has a foreach loop for stepping through a collection without managing an index, you'll meet it properly in the Arrays lesson next, and it plays the exact same role as Java's enhanced for-loop or PHP's foreach.

Example
using System;

class Program {
    static void Main() {
        int total = 0;
        for (int i = 1; i <= 5; i++) {
            total += i;
        }
        Console.WriteLine($"Total: {total}");
    }
}
Output
Total: 15
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account