Friday, April 4, 2008

C#. No3 - Control Statements - Selection

/resource from http://www.csharp-station.com/

The if Statement

forms of the if statement: IfSelection.cs
using System;
class IfSelect
{
public static void Main()
{
string myInput;
int myInt;

Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);

// Single Decision and Action with brackets
if (myInt > 0)
{
Console.WriteLine("Your number {0} is greater than zero.", myInt);
}

// Single Decision and Action without brackets
if (myInt <>

// Either/Or Decision
if (myInt != 0)
{
Console.WriteLine("Your number {0} is not equal to zero.", myInt);
}
else
{
Console.WriteLine("Your number {0} is equal to zero.", myInt);
}

// Multiple Case Decision
if (myInt < myint ="="> else if (myInt > 0 && myInt <= 10) { Console.WriteLine("Your number {0} is in the range from 1 to 10.", myInt); } else if (myInt > 10 && myInt <= 20) { Console.WriteLine("Your number {0} is in the range from 11 to 20.", myInt); } else if (myInt > 20 && myInt <= 30) { Console.WriteLine("Your number {0} is in the range from 21 to 30.", myInt); } else
{
Console.WriteLine("Your number {0} is greater than 30.", myInt);
}
}
}

The switch Statement

Switch Statements: SwitchSelection.cs

using System;
class SwitchSelect
{
public static void Main()
{
string myInput;
int myInt;

begin:

Console.Write("Please enter a number between 1 and 3: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);

// switch with integer type
switch (myInt)
{
case 1:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 2:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 3:
Console.WriteLine("Your number is {0}.", myInt);
break;
default:
Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
break;
}

decide:

Console.Write("Type \"continue\" to go on or \"quit\" to stop: ");
myInput = Console.ReadLine();

// switch with string type
switch (myInput)
{
case "continue":
goto begin;
case "quit":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("Your input {0} is incorrect.", myInput);
goto decide;
}
}
}
C# Branching Statements
Branching statement Description
break Leaves the switch block
continue Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if loop should be executed again from the beginning. Works only if switch statement is in a loop.
goto Leaves the switch block and jumps directly to a label of the form ":"
return Leaves the current method.
throw Throws an exception.

0 comments: