C# for loops
In this chapter you will learn:
- C# for loops
- Syntax of for loop
- Example of for loop
- Example for nested for loop
- Control variabls in for loop
- Omit for loop part
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 w w w. ja va2 s .c o m
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; // www . ja v a 2 s .c om
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;/* ww w .ja v a 2 s.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:
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;//w w w .ja v a 2 s.com
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:
- What is foreach statement
- How to create foreach loop statement
- Example for foreach loop
- Use break with a foreach
- Use foreach on a two-dimensional array
- Search an array using foreach
- Note for foreach loop