Sunday, April 11, 2010

Explaining Control Structures of C#

Using the if-else Statement
The if-else statement adds a path for the false evaluation of the Boolean expression.
int i = 3;
int j = 0;
int k = 0;
if ( i > 2 )
{
j = 3;
}
else
{
j = 4;
k = 5;
}

Using the switch case Statement
You can also use a goto statement, although most
programmers frown on using them. Here are two examples:
int j = 0;
int i = 1;
switch ( i )
{
case 1:
j = 7;
break;
case 2:
case 3:
j = 22;
break;
default:
j = 33;
break;
}
string lastName = "";
string text = "fred";
switch ( text )
{
case "fred":
lastName = "Flinstone";
break;
case "barney":
lastName = "Rubble";
break;
default:
lastName = "Slate";
break;
}

Using the for Statement


for ( int i = 0; i < 5; i++ )
{
Console.WriteLine( "I will not talk in class" );
}