C# for/foreach Loop
A for loop is a repetition control structure that allows you to write a loop that executes a specific number of times.
Syntax
The syntax for a for loop in C#:
for (init; condition; increment)
{
statement(s);
}
Here is the control flow of the for loop:
init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also leave this empty as long as there is a semicolon.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop is not executed and control jumps to the next statement after the for loop.
After the body of the for loop executes, the control flows to the increment statement. This statement allows you to update the loop control variables. This statement can be left empty as long as there is a semicolon after the condition.
The condition is evaluated again. If it is true, the loop executes and the process repeats (loop body, then increment step, then condition evaluation). When the condition becomes false, the for loop terminates.
Flowchart
Example
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* for loop execution */
for (int a = 10; a < 20; a = a + 1)
{
Console.WriteLine("Value of a: {0}", a);
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
foreach
C# also supports the foreach loop, which is used to iterate over arrays or collections of objects.
The following example has three parts:
Outputting elements of an integer array using a foreach loop.
Outputting elements of an integer array using a for loop.
Using a foreach loop to set a counter for array elements.
Example
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
// Similar to foreach loop
for (int i = 0; i < fibarray.Length; i++)
{
System.Console.WriteLine(fibarray[i]);
}
System.Console.WriteLine();
// Setting a counter for elements in the collection
int count = 0;
foreach (int element in fibarray)
{
count += 1;
System.Console.WriteLine("Element #{0}: {1}", count, element);
}
System.Console.WriteLine("Number of elements in the array: {0}", count);
}
}
The output is:
0
1
1
2
3
5
8
13
0
1
1
2
3
5
8
13
Element #1: 0
Element #2: 1
Element #3: 1
Element #4: 2
Element #5: 3
Element #6: 5
Element #7: 8
Element #8: 13
Number of elements in the array: 8
More information on foreach can be found at: Usage of foreach in C#