C# for
loop is a control flow statement that allows you to execute a block of code repeatedly, based on a condition. It is useful for iterating over a fixed set of values or repeating a set of instructions a certain number of times.
for
loops have clauses for initialization and iteration of a loop variable.
The syntax of a C# for
loop is as follows:
for (initialization; condition; Iteration(increment / decrement))
{
// Statements to Execute
}
The for
loop contains the following three optional sections, separated by a semicolon (;
):
true
, it will execute the body.
The body of statements to be executed on each iteration of the loop are contained within the code block defined by the opening ({
) and closing (}
) braces.
The following prints the numbers 0 through 2:
for (int i = 0; i < 3; i++)
{
Console.WriteLine ("i = " + i);
}
A key point to note in creating loops is that any variables defined within the body of a loop are only visible to code within the loop. This is concept known as scope. If, for example, a variable myCounter
is defined in a for loop, that variable ceases to exist once the loop terminates.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// variable myCounter does not yet exist
for (int i = 0; i < 10; i++)
{
int myCounter = 0; //myCounter variable created in scope of for loop
myCounter += i;
}
// after loop exit variable myCounter is now out of scope and ceases to exist
Console.ReadLine();
}
}
}
Output:
A nested for loop in C# is a for loop
inside another for loop
. The outer loop controls the number of iterations, while the inner loop performs a set of iterations on each outer loop iteration.
Following is an example of a nested for loop that prints a multiplication table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write("{0,4}", i * j);
}
Console.WriteLine();
}
}
}
}
Output:
A loop becomes infinite loop if a condition never becomes false
. The for
loop is traditionally used for this purpose. Since none of the three expressions that form the for
loop are required, you can make an endless loop by leaving the conditional expression empty
.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
for (;;)
{
Console.WriteLine("[X].DeveloperSpace");
}
Console.ReadLine();
}
}
}
Output:
When the conditional expression is absent, it is assumed to be true
. You may have an initialization and increment expression, but programmers more commonly use the for(;;)
construct to signify an infinite loop.
In C#, a for loop
can contain multiple expressions in its header section, separated by commas (,
). These expressions include an initialization expression, a condition expression, and an iterator expression.
Following is an example of a for loop with multiple expressions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine("i = {0}, j = {1}", i, j);
}
Console.ReadLine();
}
}
}
In the above example, the loop has two expressions in the initialization section, where the variable i
is initialized to 0, and the variable j
is initialized to 10. The loop also has two expressions in the iterator section, where the i
variable is incremented by 1, and the j
variable is decremented by 1 on each iteration. The loop continues to execute as long as the condition i < j
is true.
Output:
Multiple expressions in a for loop can be useful when you need to initialize or manipulate multiple variables in the loop header or iterator sections. However, it's important to ensure that these expressions are properly separated and do not conflict with each other to avoid unexpected results.
continue
statement is used to skip over the execution part of loop on a certain condition and move the flow to next updation part.
The continue statement can be used in any type of loop, including for
, while
, and do-while
loops.
For Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
{
if ((i % 2) != 0)
continue;
Console.WriteLine("[X].DevSpace: i = "+i);
}
Console.ReadLine();
}
}
}
Output:
In the example, if i
is not divisible by 2 with 0 remaining the code performs a continue sending execution to the top of the for loop, thereby bypassing the code to output the value of i
. This will result in the following output:
You can also exit from a for loop by using the break
keyword.
The break
statement is used to immediately terminate the loop, causing control to be transferred to the next statement after the loop. The break statement can be used in any type of loop, including for
, while
, and do-while
loops.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
break;
Console.WriteLine("Value of i: {0}", i);
}
Console.ReadLine();
}
}
}
Output: