C# for Loop with Examples

How to write "for" loop in C# with some examples using increment, decrement, and custom step loop

In a C# for-loop, we’re basically just stepping through a bunch of numbers. Keep in mind that for hands you an index variable, which is actually pretty handy for other stuff.

In C#, using foreach is usually the most straightforward way to loop. But if you actually need that index (like 0, 1, or 2), for is the way to go. It lets you peek at neighboring items or even mess with other lists.

In this post, I’ll show you how easy it is to write for-loop using C#.

Quickstart with Increment for-loop in C#

Using the variable i is just a common shorthand that helps other devs instantly grasp what your code is doing.

  • Start: You generally kick things off at 0 because C# collections start counting from zero rather than one.
  • Next: The loop keeps hitting the code block until i reaches 10, string length, List.Count, or whatever limit you’ve decided to set.
  • Increment / Decrement: Don’t forget that third part of the loop, the i++ (or i-- for decrement), which bumps up the count after every single lap.
using System;

for (var i = 0; i < 3; i++)
{
    Console.WriteLine($"Hello number {i}");
}

// OUTPUT:
//   Hello number 0
//   Hello number 1
//   Hello number 2

How to do Decrement Loop in C#

Imagine we want to count down from a high number to a lower one.

You can just tell your for-loop to subtract a bit during every step instead of adding. In this case, we’d kick things off at 5 and keep rolling until we hit 0.

In this C# code example, we will make a simple bomb countdown using a decrement for-loop.

using System;

for (int i = 5; i >= 0; i--)
{
    Console.WriteLine($"The Bomb will be exploded in {i}");
}

// OUTPUT:
//  The Bomb will be exploded in 5
//  The Bomb will be exploded in 4
//  The Bomb will be exploded in 3
//  The Bomb will be exploded in 2
//  The Bomb will be exploded in 1
//  The Bomb will be exploded in 0

Change the Iteration Step

The third part of the for-loop in C# is what handles the step. You can tweak the variable by any amount you want. You aren’t even stuck using a constant.

In this C# code example, we print all odd numbers below 10 using for-loop and +=2 iteration step.

using System;

for (int i = 1; i < 10; i += 2)
{
    Console.WriteLine($"{i} is an odd Number");
}

// OUTPUT:
//  1 is an odd Number
//  3 is an odd Number
//  5 is an odd Number
//  7 is an odd Number
//  9 is an odd Number

Final Thoughts

Thanks for reading and see you on my next blog post!

Cheers!

References