Friday, October 15, 2010

Understanding the for loop in c sharp.

The for loop structure is used to execute a block of statements for a specific number of times. The for loop in C# is useful for iterating over arrays and for sequential processing. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true.

Syntax of the for loop.

for(initialization; termination; increment/decrement)
{
Statements
}

Note: -the initialization expression initializes the for loop construct. It is executed once at the beginning of the loop. The termination determines when to terminate the loop. At the beginning of the loop, this expression is evaluated for each iteration. When the expression evaluates to false, the loop terminates. Then, through the loop, the increment or decrement expression gets invoked after each iteration.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace for_loop
{
class variable
{
static void Main(string[] args)
{
int var;
for (var = 10; var <= 20; var++)
{
Console.WriteLine("value of variable is: {0}", var);
Console.ReadLine();
}
}
}
}

Output of the preceding code is display below.
Value of variable is: 10
Value of variable is: 11
Value of variable is: 12
Value of variable is: 13
Value of variable is: 14
Value of variable is: 15
Value of variable is: 16
Value of variable is: 17
Value of variable is: 18
Value of variable is: 19
Value of variable is: 20



C Sharp Statements Related Contents.

How to use do…while loop in C #.
Understanding the while loop in c sharp.
Understanding the Switch… case construct in C sharp.
if...else construct in c sharp.

No comments:

Recent Posts