for loop

In this chapter you will learn:

  1. Get to know the for loop syntax
  2. Control variabls in for loop
  3. Omit for loop part

for loop syntax

You can repeatedly execute a sequence of code by creating a loop. The general form of the for loop for repeating a single statement is

for(initialization; condition; iteration) { statement sequence }
  • 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 the for loop.
  • iteration is executed after each loop iteration. iteration is usually used to update the loop-control variable.

The following code uses the for loop the print the value from 0 to 9.

using System;//from ja v a 2  s.c  o  m

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i);
        }

    }
}

The output:

Control variabls in for loop

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;// java2s  .  com

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:

Omit for loop part

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;/*from j a  v  a2  s. c  o  m*/

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        for (; i < 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use foreach loop
  2. Use break with a foreach
  3. Use foreach on a two-dimensional array
  4. Search an array using foreach
Home » C# Tutorial » Statements
Comments
if Statement
while loop
do...while loop
for loop
foreach
switch
break
continue statement
goto statement
Xml Documentation