CSharp - Statement for loops

Introduction

A for loop contains three clauses as follows:

for (initialization; condition; iteration)
       statement;
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.

Demo

using System;
class MainClass//from w w w  . j a  v  a2s  .  com
{
   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;
         }

   }
}

Result

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");

Quiz

Exercise