C# for loops
Description
for
loops are like while loops with special clauses for initialization and iteration of
a loop variable.
Syntax
The syntax is:
for (initializer; condition; iterator)
statement(s)
where:
initialization
executes first and it if often used to declare the loop control value.condition
controls the loop body execution. If condition is false, C# starts executing the statement after thefor
loop.iteration
is executed after each loop iteration. iteration is usually used to update the loop-control variable.
Example
The following code uses the for loop the print the value from 0 to 9.
using System;//from www. j a v a2s .c om
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
The output:
Example 2
Example for nested for loop
using System; /*from ww w.j a v a 2 s . c o m*/
class MainEntryPoint
{
static void Main(string[] args)
{
// This loop iterates through rows
for (int i = 0; i < 100; i+=10)
{
// This loop iterates through columns
for (int j = i; j < i + 10; j++) {
Console.Write(" " + j);
}
Console.WriteLine();
}
}
}
The code above generates the following result.
Example 3
i
is the loop-control variable.
The scope of i
is the for statement.
You cannot use i
outside.
We can put more variables in the initialization section.
using System;/*from w w w. j ava2 s. c o m*/
class Program
{
static void Main(string[] args)
{
for (int i = 0, prevFib = 1, curFib = 1; i < 20; i++)
{
Console.WriteLine(prevFib);
int newFib = prevFib + curFib;
prevFib = curFib;
curFib = newFib;
Console.WriteLine(curFib);
}
}
}
The output:
Example 4
You can omit any parts of the for loop, the initialization, condition or iteration. The following example defines the loop-control variable outside for statement.
using System;// ww w . ja va2 s.c om
class Program
{
static void Main(string[] args)
{
int i = 0;
for (; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
The output: