The last type of loop to look at in this tutorial is the for loop. This type of loop executes a set number of times and maintains its own counter. To define a for loop you need the following information:
1) A starting value to initialize the counter variable.
2) A condition for continuing the loop, involving the counter variable.
3) An operation to perform on the counter variable at the end of each loop cycle.
For example, if you want a loop with a counter that increments from 1 to 10 in steps of one, then the starting value is 1; the condition is that the counter is less than or equal to 10; and the operation to perform at the end of each cycle is to add 1 to the counter. This information must be placed into the structure of a for loop as follows:
Syntax
for ( < initialization > ; < condition > ; < operation > ) { < code to loop > }
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; ++i) { Console.WriteLine("{0}", i); } } } }