Tuesday, January 17, 2012

Iteration Statements

You can create loops by using the iteration statements. Iteration statements cause embedded statements to be executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except when a jump statement is encountered.

The following keywords are used in iteration statements:
-do
-for
-foreach
-in
-while

For Iterations
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.

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

namespace forloop
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);

}
Console.ReadLine();
}
}
}

Output :
0
1
2
3
4
5
6
7
8
9

You can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.
You also can exit the loop by using a goto, return, or throw statement.

Foreach,in statements
The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) interface.

eg:
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
/*
Output:
0
1
1
2
3
5
8
13
*/

While statement
The while statement executes a statement or a block of statements until a specified expression evaluates to false.

eg:
class WhileTest
{
static void Main()
{
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
console.ReadLine();
}
}

Output:
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5


do statement
The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The body of the loop must be enclosed in braces, {}, unless it consists of a single statement. In that case, the braces are optional.

eg:
namespace dowhile
{
class Program
{
static void Main(string[] args)
{
int x = 0;
do
{

Console.WriteLine(x);
x++;
}
while (x < 5);
Console.ReadLine();
}
}
}
Output
0
1
2
3
4

No comments:

Post a Comment