The if statement
The if-statement is a selection statement.
It directs the control flow of your C# program.
It is translated to intermediate language instructions called branches.
It makes a logical decision based on a parameter or a user's input.
Expressions in an if-statement evaluate always to true or false.
Example: Find the greater of two numbers using if statement?
class Program
{
public static void Main()
{
int
a, b;
Console.WriteLine("Enter two numbers: ");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
if
(a > b)
{
Console.WriteLine("{0} is greater than {1}", a, b);
}
else
if (a < b)
{
Console.WriteLine("{0} is greater than {1}", b, a);
}
else
{
Console.WriteLine("Both are equal");
}
Console.ReadLine();
}
}
The switch statement
The switch statement selects for execution a statement list having an associated switch label that corresponds to the value of the switch expression.
- switch-statement:
- switch ( expression ) switch-block
- switch-block:
- { switch-sectionsopt }
- switch-sections:
- switch-section
switch-sections switch-section - switch-section:
- switch-labels statement-list
- switch-labels:
- switch-label
switch-labels switch-label - switch-label:
- case constant-expression :
default :
switch
, followed by a parenthesized expression (called the switch expression), followed by a switch-block. The switch-block consists of zero or more switch-sections, enclosed in braces. Each switch-section consists of one or more switch-labels followed by a statement-listExample:
Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
default:
Console.WriteLine("I'm sorry, I don't understand that!");
break;
}
Next Chapter
No comments:
Post a Comment