Вы находитесь на странице: 1из 12

Programming C# 2.0, 3.0, 4.

Muhammed Ali Sakhi


Microsoft Certified Trainer

© PakDev.net
Agenda
Conditional Statements
If and switch
Iteration Statements
For, while, and do while

© PakDev.net
The if Statement
Syntax:
if ( Boolean-expression )
first-embedded-statement
else
second-embedded-statement

No implicit conversion from int to bool


int x;
...
if (x) ... // Must be if (x != 0) in C#
if (x = 0) ... // Must be if (x == 0) in C#
 

© PakDev.net
Cascading if Statements

enum Suit { Clubs, Hearts, Diamonds, Spades }


Suit trumps = Suit.Hearts;
if (trumps == Suit.Clubs)
color = "Black";
else if (trumps == Suit.Hearts)
color = "Red";
else if (trumps == Suit.Diamonds)
color = "Red";
else
color = "Black";

© PakDev.net
The switch Statement
Use switch statements for multiple case blocks
Use break statements to ensure that no fall
through occurs

switch (trumps) {
case Suit.Clubs :
case Suit.Spades :
color = "Black"; break;
case Suit.Hearts :
case Suit.Diamonds :
color = "Red"; break;
default:
color = "ERROR"; break;
}

© PakDev.net
The for Loop
Execute embedded statements based on
Boolean value
Evaluate Boolean expression after every
increment or after initialization
Execute embedded statements while Boolean
value Is True

For(int i=0; i<10; i++) {


Console.WriteLine(i);
}

0 1 2 3 4 5 6 7 8 9
© PakDev.net
The while Loop
Execute embedded statements based on
Boolean value
Evaluate Boolean expression at beginning of loop
Execute embedded statements while Boolean
value Is True

int i = 0;
while (i < 10) {
Console.WriteLine(i);
i++;
}

0 1 2 3 4 5 6 7 8 9
© PakDev.net
The do while Loop
Execute embedded statements based on
Boolean value
Evaluate Boolean expression at end of loop
Execute embedded statements while Boolean
value
Is True
int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 10);

0 1 2 3 4 5 6 7 8 9
© PakDev.net
The for Statement
Place update information at the start of the loop

for (int i = 0; i < 10; i++) {


Console.WriteLine(i);
} Variables in a for block are scoped only within the block
0 1 2 3 4 5 6 7 8 9

for A(int i can


for loop = 0; i < over
iterate 10;several
i++) values
Console.WriteLine(i);
Console.WriteLine(i); // Error: i is no longer in scope

for (int i = 0, j = 0; ... ; i++, j++)

© PakDev.net
Conditions and Loops

Demo

© PakDev.net
Demonstration Steps
Create a console application
Validate a day number from user input
Write a line 10 times
Write a line until user says no
Write a line at least once, and then until user
says no

© PakDev.net
Thank you
PakDev.net

© PakDev.net

Вам также может понравиться