for Loop in C#: Build a Sales Grid Step by Step (.NET 10)

Four stores, six months, one grid: that’s what our Phoenix regional manager asked for. A for loop in C# repeats code a set number of times with a counter: for (int i = 0; i < n; i++) { ... }.

In this tutorial, I’ll show you, one small step at a time, how the for loop in C# counts forward, backward and by steps, nests for a table, and uses break and continue to build that grid on .NET 10.

Here’s what we’re building. Each row is a store, each column is a month in thousands of dollars, and the last column is the store’s total:

for loop in C# nested loops printing a store sales grid for Austin, Denver, Phoenix and Tampa in VS Code
The finished grid: an outer loop over stores, an inner loop over months

Before You Start the for Loop Build

You need the .NET 10 SDK and an editor. I run every step as a single-file app with dotnet run File.cs; if that’s new to you, here’s how to create a console application in Visual Studio Code.

All steps share this sample data (sales in thousands of USD, January to June 2026):

StoreJanFebMarAprMayJun
Austin, TX423851475358
Denver, CO29330363134
Phoenix, AZ554958616470
Tampa, FL313530403844

Denver’s March is 0 because the store closed for a remodel. We’ll use that gap in Step 5.

Step 1: Write a Basic for Loop (Initializer, Condition, Iterator)

A for header has three sections separated by semicolons. Let’s walk the months forward:

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];

//   initializer; condition;         iterator
for (int m = 0;   m < months.Length; m++)
{
    Console.WriteLine($"Month {m}: {months[m]}");
}
Console.WriteLine($"The loop ran {months.Length} times");

Output:

Month 0: Jan
Month 1: Feb
Month 2: Mar
Month 3: Apr
Month 4: May
Month 5: Jun
The loop ran 6 times
C# for loop over a months array showing the initializer, condition and iterator sections in VS Code
Six passes, one per month, counter m from 0 to 5

Here’s the order C# runs the pieces in, per the Microsoft reference:

  1. Initializer int m = 0 runs once, before the first pass.
  2. Condition m < months.Length is checked before every pass; false ends the loop.
  3. The body runs.
  4. The iterator m++ runs, then it’s back to the condition.

m only exists inside the loop, so you can’t read it after the closing brace. My guide to arrays in C# covers Length and indexes in more depth.

Checkpoint: Month 0: Jan through Month 5: Jun, then The loop ran 6 times.

Step 2: Loop Backward with a Decrementing Counter

The manager wants the newest month first. Start at the last index, keep going while m >= 0, and count down:

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];

for (int m = months.Length - 1; m >= 0; m--)
    Console.Write($"{months[m]} ");
Console.WriteLine("<- newest first");

Output:

Jun May Apr Mar Feb Jan <- newest first

The last index is Length - 1, not Length. If you only need the array flipped, there’s a shortcut to reverse an array in C# without writing the loop.

Checkpoint: Jun May Apr Mar Feb Jan <- newest first.

Step 3: Step by 2 or 3 in a for Loop

The iterator can be any assignment, so m += 3 jumps a whole quarter at a time. Same Austin row, now as quarter totals:

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[] austin = [42, 38, 51, 47, 53, 58];   // $ thousands

for (int m = 0; m < austin.Length; m += 3)
{
    int q = austin[m] + austin[m + 1] + austin[m + 2];
    Console.WriteLine($"Q{m / 3 + 1} {months[m]}-{months[m + 2]}: ${q}K");
}

Console.Write("Every 2nd month:");
for (int m = 1; m < months.Length; m += 2)
    Console.Write($" {months[m]}");
Console.WriteLine();

Output:

Q1 Jan-Mar: $131K
Q2 Apr-Jun: $158K
Every 2nd month: Feb Apr Jun
C# for loop with m += 3 adding quarterly sales and m += 2 printing every second month, VS Code output
m += 3 visits Jan and Apr; m += 2 starting at 1 visits Feb, Apr, Jun

The start value and the step together decide which items you touch.

Checkpoint: Q1 Jan-Mar: $131K, Q2 Apr-Jun: $158K, then Feb Apr Jun.

Step 4: Nest for Loops to Print the Grid

Now the full table. The outer loop walks the rows (stores); for each row, the inner loop walks the columns (months):

string[] stores = ["Austin", "Denver", "Phoenix", "Tampa"];
string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[,] sales = { { 42, 38, 51, 47, 53, 58 },
                 { 29, 33,  0, 36, 31, 34 },
                 { 55, 49, 58, 61, 64, 70 },
                 { 31, 35, 30, 40, 38, 44 } };   // $ thousands

for (int s = 0; s < sales.GetLength(0); s++)    // stores
{
    Console.Write($"{stores[s],-8}");
    for (int m = 0; m < sales.GetLength(1); m++)  // months
        Console.Write($"{sales[s, m],4}");
    Console.WriteLine();
}

Output:

Austin    42  38  51  47  53  58
Denver    29  33   0  36  31  34
Phoenix   55  49  58  61  64  70
Tampa     31  35  30  40  38  44
C# nested for loop over a 2D int array using GetLength(0) and GetLength(1) printing a store by month grid
GetLength(0) is the row count, GetLength(1) the column count

On a two-dimensional array, Length is the total cell count (24 here), so use GetLength(0) and GetLength(1) for each dimension. The ,4 in the interpolation right-aligns each number; more options are in format numbers with commas and decimals in C#.

Checkpoint: four rows of six numbers, with Phoenix’s row ending in 70.

Step 5: Use break and continue in a for Loop

Two questions from the manager: what did Denver average in the months it was open, and when did Phoenix first top $60K?

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[] denver = [29, 33, 0, 36, 31, 34];
int[] phoenix = [55, 49, 58, 61, 64, 70];

int total = 0, open = 0;
for (int m = 0; m < denver.Length; m++)
{
    if (denver[m] == 0) continue;   // closed for remodel
    total += denver[m]; open++;
}
Console.WriteLine($"Denver: ${total}K over {open} open months");

for (int m = 0; m < phoenix.Length; m++)
{
    if (phoenix[m] < 60) continue;
    Console.WriteLine($"Phoenix hit $60K in {months[m]}"); break;
}

Output:

Denver: $163K over 5 open months
Phoenix hit $60K in Apr
C# for loop where continue skips Denver's closed month and break stops at Phoenix's first $60K month, VS Code
continue skips March in Denver; break stops the Phoenix loop at April

continue jumps straight to the iterator, so the closed month isn’t counted. break leaves the loop at once, and May and June are never read.

Note: if every month were closed, open would be 0, so check it before you divide. That’s the division by zero exception in C# waiting to happen.

Checkpoint: Denver: $163K over 5 open months and Phoenix hit $60K in Apr.

Step 6: Declare Multiple Variables in the for Loop Initializer

To compare each early month with its mirror late month, use two counters: one moving forward, one moving back.

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[] phoenix = [55, 49, 58, 61, 64, 70];

for (int first = 0, last = months.Length - 1; first < last; first++, last--)
{
    int change = phoenix[last] - phoenix[first];
    Console.WriteLine($"{months[first]} vs {months[last]}: {change:+0;-0}K");
}

Output:

Jan vs Jun: +15K
Feb vs May: +15K
Mar vs Apr: +3K

You can declare several variables of the same type with commas, and the iterator can update both: first++, last--. It’s the same two-index pattern I use to swap two numbers in C# inside an array.

Checkpoint: Jan vs Jun: +15K, Feb vs May: +15K, Mar vs Apr: +3K.

Test the Finished for Loop Sales Grid

Here’s the full program from the top screenshot. After a header line, the nested loops print each store and its total:

string[] stores = ["Austin", "Denver", "Phoenix", "Tampa"];
string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
int[,] sales = { { 42, 38, 51, 47, 53, 58 },
                 { 29, 33,  0, 36, 31, 34 },
                 { 55, 49, 58, 61, 64, 70 },
                 { 31, 35, 30, 40, 38, 44 } };   // $ thousands
Console.WriteLine("Store    Jan  Feb  Mar  Apr  May  Jun Total");
for (int s = 0; s < stores.Length; s++)
{
    int total = 0;
    Console.Write($"{stores[s],-7}");
    for (int m = 0; m < months.Length; m++)
    {
        Console.Write($"{sales[s, m],5}");
        total += sales[s, m];
    }
    Console.WriteLine($"{total,6}");
}

Output:

Store    Jan  Feb  Mar  Apr  May  Jun Total
Austin    42   38   51   47   53   58   289
Denver    29   33    0   36   31   34   163
Phoenix   55   49   58   61   64   70   357
Tampa     31   35   30   40   38   44   218

total is declared inside the outer loop, so it resets to 0 for every store. Phoenix leads with $357K, and Denver’s $163K reflects the closed month.

for vs foreach in C#: Which Should You Use?

Both loops can walk the months array. I pick by what I need from the loop; the foreach loop in C# builds the same kind of report without an index.

forforeach
Index availableYes, the counterNo (use Index() on .NET 9+)
Backward or step by NYesNo
Write to array itemsYes, months[m] = ...No, loop variable is read-only
Works onArrays, lists (use Count)Any enumerable
Off-by-one riskYesNo

Why Does My for Loop Throw IndexOutOfRangeException?

Almost always it’s <= where you meant <. Arrays are zero-based, so a six-item array has indexes 0 to 5:

string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];

for (int m = 0; m <= months.Length; m++)   // <= is the bug
    Console.WriteLine(months[m]);

Output (unhandled exception):

Jan
Feb
Mar
Apr
May
Jun
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Program.<Main>$(String[] args) in C:\DotNetDemo\ForLoopDemo\OffByOne.cs:line 4
C# for loop off-by-one error with m <= months.Length throwing IndexOutOfRangeException in VS Code terminal
All six months print, then index 6 throws

Important: write the condition as i < array.Length going forward and start at array.Length - 1 going backward.

Troubleshooting: Infinite for Loops

All three sections are optional, so for (;;) runs until something inside calls break. Here it projects when Phoenix reaches $80K at 5% growth a month:

decimal forecast = 70m;   // Phoenix June sales, $ thousands
int monthsAhead = 0;
for (;;)
{
    if (forecast >= 80m) break;
    forecast *= 1.05m;     // 5% growth a month
    monthsAhead++;
}
Console.WriteLine($"$80K reached in {monthsAhead} months");

Output:

$80K reached in 3 months

It works, but when the exit depends on a value instead of a count, I’d write a while loop in C#. An accidental infinite loop usually means the iterator moves away from the condition, like i-- with i < n.

Where to Take It Next with for Loops

If you’re comparing loop types, these are worth reading next:

Frequently Asked Questions

What is the syntax of a for loop in C#?

for (initializer; condition; iterator) { body }. For example, for (int i = 0; i < 5; i++) runs the body five times with i from 0 to 4.

Can a C# for loop have two variables?

Yes. Declare them in the initializer with commas, such as int i = 0, j = 10, and update both in the iterator with i++, j--. They must share one type when you declare them there.

How do I loop backward in C#?

Start at the last index and count down: for (int i = arr.Length - 1; i >= 0; i--). Starting at arr.Length throws IndexOutOfRangeException.

What is the difference between break and continue in a for loop?

break exits the loop completely. continue skips the rest of the current pass and goes to the iterator, then the condition.

Is a for loop faster than foreach in C#?

For arrays the compiler generates nearly identical code, and for List<T> the difference is tiny. Choose the loop that reads best and measure only if a profiler points at it.

Are all parts of a for loop optional?

Yes. Microsoft’s iteration statements reference notes every section is optional, so for (;;) is an infinite loop that needs a break.