Conditional Control
if Statement
The if statement implements conditional execution. Syntax:if([Test Expression])
[statement]
Example:
int x = 10; int maxValue = 5; if (x > maxValue) { maxValue = x; Console.WriteLine("x is bigger than maxValue"); }
if...else Statement
Theif
...else
statement implements a two-way branch. The syntax for the if...else statement is:
if([Test Expression])
[statement1]
else
[statement2]
Example:
int x = 10; int maxValue = 5; if (x > maxValue) { maxValue = x; Console.WriteLine("x is bigger than maxValue"); } else Console.WriteLine("x is less than maxValue");
switch Statement
Theswitch
statement implements multiway branching,with following syntax
switch([Test Identifier])
{
case [Condition 1]:
[statement 1]
case [Condition 2]:
[statement 2]
....
case [Condition n]:
[statement n]
[default:Optional]:
[statement default:Optional]
}
int numWheel = 4; switch (numWheel) { case 1: Console.WriteLine("Monocycle"); break; case 2: Console.WriteLine("Bicycle"); break; case 3: Console.WriteLine("Auto Rickshaw"); break; case 4: Console.WriteLine("Car"); break; default: Console.WriteLine("Maybe Train"); break; }
Unlike C and C++, in C# each switch section, including the optional default section, must end with one of the jump statements.
In C#, you cannot execute the code in one switch section and then fall through to the next.
Loop Control
while loop
Thewhile
loop is a simple loop construct in which the test expression is performed at the top of the loop.
The syntax of the while loop is:
while([Test Expression])
[statement]
Example:
int x = 10; while (x < 0) { Console.WriteLine("Counting down " + x); --x; } Console.WriteLine("Now x :" + x);
do...while Loop
Thedo
...while
loop is a simple loop construct in which the test expression is performed at the bottom of the loop. Syntax:
do
{
[statement]
}
while([Test Expression])
Example:
int x = 10; do { Console.WriteLine("Counting down " + x); --x; }while (x < 0) Console.WriteLine("Now x :" + x);
for Loop
Thefor
loop construct executes the body of the loop as long as the test expression returns true when it is evaluated
at the top of the loop. The syntax of the for loop is
for ([Initializer] ; [Test Expression] ; [Iteration Expression])
[Statement]
Example:
for(int x = 10; x < 0 ; --x) { Console.WriteLine("Counting down " + x); }
0 comments:
Post a Comment