for loop
In this chapter you will learn:
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 thefor
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:
- How to use foreach loop
- Use break with a foreach
- Use foreach on a two-dimensional array
- Search an array using foreach