CSharp - Statement for loops


A for loop contains three clauses as follows:

for (initialization; condition; iteration)
Clause Description
Initialization Executed before the loop begins; initialize one or more iteration variables.
Conditionwhile condition is true, it will execute the body.
IterationExecuted after each iteration of the statement; update the iteration variable.

The following prints the numbers 0 through 2:

for (int i = 0; i < 3; i++)
       Console.WriteLine (i);

The following prints the first 10 Fibonacci numbers.

Each number is the sum of the previous two numbers in Fibonacci.


using System;
class MainClass//www .  j  a  va 2s . co  m
   public static void Main(string[] args)
         for (int i = 0, prevFib = 1, curFib = 1; i < 10; i++)
           Console.WriteLine (prevFib);
           int newFib = prevFib + curFib;
           prevFib = curFib; curFib = newFib;



Any of the three parts in for loop can be omitted.

You can implement an infinite loop such as the following.

for (;;)
   Console.WriteLine ("hi");