Sunday, April 11, 2010

C# control Statement

Using the while Statement

The while statement is also used to loop through a series of statements until a test
Boolean expression evaluated at the beginning of the loop is false.The following
code has the same result as the previous for statement example:
int i = 0;
while ( i < 5 )
{
Console.WriteLine( "I will not talk in class" );
i++;
}


Using the do while Statement


The do while statement is also used to loop through a series of until a test
Boolean expression evaluated at the end of the loop is false.Therefore, the series
of statements contained within the do while loop will always execute at least once:
int i = 6;
do
{
Console.WriteLine( "I will not talk in class" );
i++;
}
while ( i < 5 );


Using the break Statement


The break statement exits the loop of a for, while, or do while statement regardless
of value of the test Boolean expression. In each of the following examples, the
WriteLine method will execute two times:
int j = 0;
for ( int i = 0; i < 5; i++ )
{
Console.WriteLine( "I will not talk in class" );
j++;
if ( j == 2 )


break;
}
int i = 0;
int j = 0;
while ( i < 5 )
{
Console.WriteLine( "I will not talk in class" );
i++;
j++;
if ( j == 2 )
break;
}
int i = 0;
int j = 0;
do
{
Console.WriteLine( "I will not talk in class" );
i++;
j++;
if ( j == 2 )
break;
}
while ( i < 5 );

Using the continue Statement

The continue statement will pass flow of control immediately to the start of a loop
when encountered. In the following example, “I will not talk in class” will display
twice and “At least I’ll try not to talk in class” will display three times:
int j = 0;
for ( int i = 0; i < 5; i++ )
{
j++;

if ( j > 2 )
{
Console.WriteLine( "At least I'll try not to talk in class" );
continue;
}
Console.WriteLine( "I will not talk in class" );
}
Using the return Statement
The return statement returns flow of control from a method to the caller, optionally
passing back a return value. Here is a complete example:
using System;
class TestDivision
{
static void Main(string[] args)
{
int dividend = 2;
int divisor = 0;
Divider divider = new Divider();
bool ret = divider.divide( dividend, divisor );
if ( ret == true )
Console.WriteLine( "I divided!" );
else
Console.WriteLine( "Something went horribly wrong!" );
}
}
class Divider
{
public bool divide( int dividend, int divisor )
{


if ( divisor == 0 )
return false;
int result = dividend / divisor;
return true;
}
}

 If you must use goto, here is an example:
int i = 0;
int j = 0;
while ( i < 5 )
{
Console.WriteLine( "I will not talk in class" );
i++;
j++;
if ( j == 2 )
goto jumpeddoutofloop;
}
jumpeddoutofloop:
Console.WriteLine( "I jumped out" );