A for loop is used to execute the program for a fixed number of times. For loop in C# is similar to that in C, C++ or Java.
Syntax
A for loop has three parts.
- Initialization
- Condition and
- An operation to be performed each time the loop is executed.
for(int i=0; i<10; i++){
//statements
}
Working
This is how a for loop works:
- A value is initialized (only for the first time).
- An expression is evaluated.
- The body of the loop is executed if the expression is evaluated to true.
- An operation (increment or decrement) is performed.
- The above three steps are repeated until the expression is evaluated to false.
See this post to find the difference between a for loop and while loop.
Example
using System;
namespace CSharpExamples
{
class Program
{
static void Main(string[] args)
{
for(int i=0;i<=3;i++)
{
Console.WriteLine("value of i is: " + i);
}
}
}
}
This program, when executed will produce the following output:
value of i is: 0
value of i is: 1
value of i is: 2
value of i is: 3
Nested for loop
A for loop specified inside a for loop is known as a nested for loop.
Example
using System;
namespace CSharpExamples
{
class Program
{
static void Main(string[] args)
{
for(int i=2;i>=0;i--)
{
for(int j=0;j<2;j++)
{
Console.WriteLine("i = " + i + ", j = " + j);
}
}
Console.ReadLine();
}
}
}
The output of this program is:
i = 2, j = 0
i = 2, j = 1
i = 1, j = 0
i = 1, j = 1
i = 0, j = 0
i = 0, j = 1