C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The for keyword indicates a loop in C#. The for loop executes a block of statements repeatedly until the specified condition returns false.
Syntax:
for (variable initialization; condition; steps) { //execute this code block as long as condition is satisfied }
As per the syntax above, the for loop contains three parts: initialization, conditional expression and steps, which are separated by a semicolon.
Consider the following example of a simple for loop.
Example: for loop
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Value of i: {0}", i);
}
As you can see in the above example, first step is to declare & initialize an int type variable. The second step is to check the condition. The third step is to execute the code block if the 'if' condition returns true. The fourth step is to increment the int variable and last step is to eveluate the condition again and repeat the steps.
It is not necessary to put the initialization, condition and steps into brackets. You can initialize a variable before the 'for' loop, and the condition and steps can be defined inside the for loop.
Example: for loop C#
int i = 0;
for(;;)
{
if (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
else
break;
}
Be careful with infinite loop. It will be an infinite loop if for loop does not contain initialization, condition or steps part. Also, make sure that conditional expression will return false at some point of time to stop the looping.
Example: Infinite loop
for ( ; ; )
{
Console.Write(1);
}
The control variable for the for loop can be of any numeric data type, such as double, decimal, etc.
Example: for loop
for (double d = 1.01D; d < 1.10; d+= 0.01D)
{
Console.WriteLine("Value of i: {0}", d);
}
The steps part in a for loop can either increase or decrease the value of a variable.
Example: for loop
for(int i = 10; i> 0;i--)
{
Console.WriteLine("Value of i: {0}", i);
}
C# allows a for loop inside another for loop.
Example: Nested for loop
for (int i = 0; i < 10; i++)
{
for(int j =i; j< 10; j++)
Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}