C# Tutorial - Dissecting Our Second Application – for LoopsWe could implement the same functionality of the foreach loop using the more commonly used iteration statement, for, like this; using System;
using System.Collections.Generic;
using System.Text;
namespace App02
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Hello " + args[i]);
}
Console.Read();
}
}
}
The for loop is used to iterate over a block of code a fixed number of times until a terminating condition is achieved. The three fields of the for statement are normally used for initialization, testing for termination, and incrementing of a local variable. In our case the first statement creates a local variable (an integer called i)and initializes it to have a value of zero. The second statement checks to see if the value of i is less than the number of elements in the array args. Finally the third statement increments i every time that the end of the loop has been reached. In comparison to the foreach loop, the for loop requires an extra local variable to be used plus the array is then accessed dependant upon the value of the local variable. Iteration Statement - forThe for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The loop is always declared in the following manner: for( initializer ; condition ; iterator )
{
embedded-statements;
}
Where:
A simple example to print the numbers 1 to 10 would be: for( int i = 1; i <= 10; i++ )
{
Console.WriteLine( "{0},", i );
}
Would output 1,2,3,4,5,6,7,8,9,10, No ParametersIf no condition is supplied, then the loop will run forever. So the following code would give an infinite loop. for (;;)
{
// ...
}
Multiple ParametersEach of the statements may be supplied with more than one statement separated by commas. The following example shows this. for( int high = 50, int low = 0; high >= low; high--, low++)
{
// ...
}
|