# for loop — An Introduction

A for loop has two parts.

  1. header
  2. body
 

 


for (int i = 0; i < 10; i++)
{
  // Empty body
}
1
2
3
4

In this code, line 1 is the header. Code between line 2 to 4 is the body.

A header has three parts,

  1. loop variable declaration and initialization, int i = 0
  2. condition, i < 10
  3. increment, i++

The for loop keeps iterating as long as the condition is true.

Loop variable declaration and increment is optional, but condition is mandatory. This means you can write a for loop this way too,


 




int i = 0;
for (; i < 10;)
{
  i++;
}
1
2
3
4
5

WARNING

Of course, this is just an example. You should never write a for loop in this manner.

# 👎 Bad Practice

WARNING

The following style of code is bad. Do not use it.

If your loop body has a single line then you can remove the enclosing braces {}.

for (int i = 0; i < 10; i++)
  Console.WriteLine(i);
1
2

But never write a loop body without braces.

# 👍 Best Practice 1

Always enclose for loop body in braces {}


 

 

for (int i = 0; i < 10; i++)
{
  Console.WriteLine(i);
}
1
2
3
4

# 👍 Best Practice 2

We usually use i, j, and k for naming loop variables. i is the outer loop, j is the inner loop, and k is inside the j loop.







 


 


 








using System;

class MainClass
{
  public static void Main(string[] args)
  {
    for (int i = 0; i < 10; i++)
    {
      // i loop body
      for (int j = 0; j < 10; j++)
      {
        // j loop body
        for (int k = 0; k < 10; k++)
        {
          // k loop body
        }
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

You are not bound to use these letters. You can use other names in place of i, j and k.

Last Updated: Apr 22, 2020, 1:39 PM