37
Conditional Conditional Statements Statements Implementing Control Logic in C# Implementing Control Logic in C# Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com

05. Conditional Statements

Embed Size (px)

DESCRIPTION

Comparison Operators and Boolean Expressions if and if-else Statements Nested if Statements The switch-case Statement Exercises: Working with Conditional Statements

Citation preview

Page 1: 05. Conditional Statements

Conditional Conditional StatementsStatements

Implementing Control Logic in C#Implementing Control Logic in C#

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 05. Conditional Statements

Table of ContentsTable of Contents

1.1. Comparison and Logical OperatorsComparison and Logical Operators

2.2. The The ifif Statement Statement

3.3. The The if-elseif-else Statement Statement

4.4. Nested Nested ifif Statements Statements

5.5. The The switch-caseswitch-case Statement Statement

2

Page 3: 05. Conditional Statements

Comparison Comparison and Logical and Logical OperatorsOperators

Page 4: 05. Conditional Statements

Comparison OperatorsComparison Operators

4

OperatorOperator Notation in Notation in C#C#

EqualsEquals ====

Not EqualsNot Equals !=!=

Greater ThanGreater Than >>

Greater Than or EqualsGreater Than or Equals >=>=

Less ThanLess Than <<

Less Than or EqualsLess Than or Equals <=<= Example:Example:

bool result = 5 <= 6;bool result = 5 <= 6;Console.WriteLine(result); // TrueConsole.WriteLine(result); // True

Page 5: 05. Conditional Statements

Logical OperatorsLogical Operators

De Morgan lawsDe Morgan laws !!A !!A A A

!(A || B) !(A || B) !A && !B !A && !B

!(A && B) !(A && B) !A || !B !A || !B

OperatorOperator Notation in Notation in C#C#

Logical NOTLogical NOT !!

Logical ANDLogical AND &&&&

Logical ORLogical OR ||||

Logical Exclusive OR Logical Exclusive OR (XOR)(XOR) ^̂

5

Page 6: 05. Conditional Statements

ifif and and if-elseif-elseImplementing Conditional LogicImplementing Conditional Logic

Page 7: 05. Conditional Statements

The The ifif Statement Statement

The most simple conditional The most simple conditional statementstatement

Enables you to test for a conditionEnables you to test for a condition Branch to different parts of the Branch to different parts of the

code depending on the resultcode depending on the result The simplest form of an The simplest form of an ifif

statement:statement:if (condition) if (condition) {{ statements;statements;}}

7

Page 8: 05. Conditional Statements

Condition and Condition and StatementStatement

The condition can be:The condition can be: Boolean variableBoolean variable Boolean logical expressionBoolean logical expression Comparison expressionComparison expression

The condition cannot be integer The condition cannot be integer variable (like in C / C++)variable (like in C / C++)

The statement can be:The statement can be: Single statement ending with a Single statement ending with a

semicolonsemicolon Block enclosed in bracesBlock enclosed in braces 8

Page 9: 05. Conditional Statements

How It Works?How It Works?

The condition is evaluatedThe condition is evaluated If it is true, the statement is executedIf it is true, the statement is executed If it is false, the statement is skipped If it is false, the statement is skipped

truetrue

conditioncondition

statementstatement

falsfalsee

9

Page 10: 05. Conditional Statements

The The ifif Statement – Statement – ExampleExample

10

static void Main()static void Main(){{ Console.WriteLine("Enter two numbers.");Console.WriteLine("Enter two numbers.");

int biggerNumber = int biggerNumber = int.Parse(Console.ReadLine());int.Parse(Console.ReadLine()); int smallerNumber = int smallerNumber = int.Parse(Console.ReadLine());int.Parse(Console.ReadLine());

if (smallerNumber > biggerNumber)if (smallerNumber > biggerNumber) {{ biggerNumber = smallerNumber;biggerNumber = smallerNumber; }}

Console.WriteLine("The greater number is: {0}",Console.WriteLine("The greater number is: {0}", biggerNumber);biggerNumber);}}

Page 11: 05. Conditional Statements

The The ifif Statement StatementLive DemoLive Demo

Page 12: 05. Conditional Statements

The The if-elseif-else StatementStatement

More complex and useful conditional More complex and useful conditional statementstatement

Executes one branch if the condition Executes one branch if the condition is true, and another if it is false is true, and another if it is false

The simplest form of an The simplest form of an if-elseif-else statement:statement:if (expression) if (expression) {{ statement1; statement1; }}else else {{ statement2; statement2; }}

12

Page 13: 05. Conditional Statements

How It Works ?How It Works ?

The condition is evaluatedThe condition is evaluated If it is true, the first statement is executedIf it is true, the first statement is executed If it is false, the second statement is If it is false, the second statement is

executedexecuted

conditiconditionon

firstfirststatementstatement

truetrue

secondsecondstatementstatement

falsfalsee

13

Page 14: 05. Conditional Statements

if-elseif-else Statement – Statement – ExampleExample

Checking a number if it is odd or Checking a number if it is odd or eveneven

string s = Console.ReadLine();string s = Console.ReadLine();int number = int.Parse(s);int number = int.Parse(s);

if (number % 2 == 0)if (number % 2 == 0){{ Console.WriteLine("This number is even.");Console.WriteLine("This number is even.");}}elseelse{{ Console.WriteLine("This number is odd.");Console.WriteLine("This number is odd.");}}

14

Page 15: 05. Conditional Statements

The The if-elseif-else StatementStatement

Live DemoLive Demo

Page 16: 05. Conditional Statements

Nested Nested ifif Statements Statements Creating More Complex LogicCreating More Complex Logic

Page 17: 05. Conditional Statements

Nested Nested ifif Statements Statements ifif and and if-elseif-else statements can be statements can be

nestednested, i.e. used inside another , i.e. used inside another ifif or or elseelse statementstatement

Every Every elseelse corresponds to its closest corresponds to its closest preceding preceding ififif (expression) if (expression) {{ if (expression) if (expression) {{ statement;statement; }} else else {{ statement;statement; }}}}elseelse statement; statement;

17

Page 18: 05. Conditional Statements

Nested Nested ifif – Good – Good PracticesPractices

Always use Always use {{ …… }} blocks to avoid blocks to avoid ambiguityambiguity Even when a single statement followsEven when a single statement follows

Avoid using more than three levels Avoid using more than three levels of nested of nested ifif statementsstatements

Put the case you normally expect to Put the case you normally expect to process first, then write the unusual process first, then write the unusual casescases

Arrange the code to make it more Arrange the code to make it more readablereadable

18

Page 19: 05. Conditional Statements

Nested Nested ifif Statements – Statements – ExampleExample

if (first == second)if (first == second){{ Console.WriteLine(Console.WriteLine( "These two numbers are equal.");"These two numbers are equal.");}}elseelse{{ if (first > second)if (first > second) {{ Console.WriteLine(Console.WriteLine( "The first number is bigger.");"The first number is bigger."); }} elseelse {{ Console.WriteLine("The second is bigger.");Console.WriteLine("The second is bigger."); }}}}

19

Page 20: 05. Conditional Statements

Nested Nested ififStatementStatement

ssLive DemoLive Demo

Page 21: 05. Conditional Statements

Multiple if-else-if-else-Multiple if-else-if-else-……

Sometimes we need to use another Sometimes we need to use another ifif-construction in the -construction in the elseelse block block Thus Thus else ifelse if can be used: can be used:

21

int ch = 'X';int ch = 'X';

if (ch == 'A' || ch == 'a')if (ch == 'A' || ch == 'a')

{{

Console.WriteLine("Vowel [ei]");Console.WriteLine("Vowel [ei]");

}}

else if (ch == 'E' || ch == 'e')else if (ch == 'E' || ch == 'e')

{{

Console.WriteLine("Vowel [i:]");Console.WriteLine("Vowel [i:]");

}}

else if …else if …

else …else …

Page 22: 05. Conditional Statements

Multiple Multiple if-if-elseelse

StatementsStatementsLive DemoLive Demo

Page 23: 05. Conditional Statements

switch-caseswitch-caseMaking Several Comparisons at Making Several Comparisons at OnceOnce

Page 24: 05. Conditional Statements

The The switch-caseswitch-case StatementStatement

Selects for execution a statement Selects for execution a statement from a list depending on the value of from a list depending on the value of the the switchswitch expression expression

switch (day)switch (day){{

case 1: Console.WriteLine("Monday"); break;case 1: Console.WriteLine("Monday"); break;case 2: Console.WriteLine("Tuesday"); break;case 2: Console.WriteLine("Tuesday"); break;case 3: Console.WriteLine("Wednesday"); break;case 3: Console.WriteLine("Wednesday"); break;case 4: Console.WriteLine("Thursday"); break;case 4: Console.WriteLine("Thursday"); break;case 5: Console.WriteLine("Friday"); break;case 5: Console.WriteLine("Friday"); break;case 6: Console.WriteLine("Saturday"); break;case 6: Console.WriteLine("Saturday"); break;case 7: Console.WriteLine("Sunday"); break;case 7: Console.WriteLine("Sunday"); break;default: Console.WriteLine("Error!"); break;default: Console.WriteLine("Error!"); break;

}}

24

Page 25: 05. Conditional Statements

How How switch-caseswitch-case Works?Works?

1.1. The expression is evaluatedThe expression is evaluated

2.2. When one of the constants specified in When one of the constants specified in a case label is equal to the expressiona case label is equal to the expression The statement that corresponds to The statement that corresponds to

that case is executedthat case is executed

3.3. If no case is equal to the expressionIf no case is equal to the expression If there is default case, it is executedIf there is default case, it is executed Otherwise the control is transferred to Otherwise the control is transferred to

the end point of the switch statement the end point of the switch statement

25

Page 26: 05. Conditional Statements

The The switch-case switch-case StatementStatement

Live DemoLive Demo

Page 27: 05. Conditional Statements

Using Using switchswitch: Rules: Rules Variables types like Variables types like stringstring, , enumenum and and

integral types can be used for integral types can be used for switchswitch expressionexpression

The value The value nullnull is permitted as a case is permitted as a case label constantlabel constant

The keyword The keyword breakbreak exits the switch exits the switch statement statement

"No fall through" rule – you are "No fall through" rule – you are obligated to use obligated to use breakbreak after each case after each case

Multiple labels that correspond to the Multiple labels that correspond to the same statement are permittedsame statement are permitted

27

Page 28: 05. Conditional Statements

Multiple Labels – Multiple Labels – ExampleExample

switch (animal)switch (animal){{ case "dog" :case "dog" : Console.WriteLine("MAMMAL"); Console.WriteLine("MAMMAL"); break;break; case "crocodile" :case "crocodile" : case "tortoise" :case "tortoise" : case "snake" : case "snake" : Console.WriteLine("REPTILE"); Console.WriteLine("REPTILE"); break;break; default : default : Console.WriteLine("There is no such Console.WriteLine("There is no such

animal!"); animal!"); break;break;}}

You can use multiple labels to execute the You can use multiple labels to execute the same statement in more than one casesame statement in more than one case

28

Page 29: 05. Conditional Statements

Multiple Multiple Labels in a Labels in a switch-caseswitch-case

Live DemoLive Demo

Page 30: 05. Conditional Statements

Using Using switchswitch – Good – Good PracticesPractices

There must be a separate There must be a separate casecase for for every normal situationevery normal situation

Put the normal case firstPut the normal case first Put the most frequently executed Put the most frequently executed

cases first and the least frequently cases first and the least frequently executed lastexecuted last

Order cases alphabetically or Order cases alphabetically or numericallynumerically

In In defaultdefault use case that cannot be use case that cannot be reached under normalreached under normal circumstancescircumstances

30

Page 31: 05. Conditional Statements

SummarySummary Comparison and logical operators are Comparison and logical operators are

used to compose logical conditionsused to compose logical conditions The conditional statements The conditional statements ifif and and if-elseif-else provide conditional execution provide conditional execution of blocks of codeof blocks of code Constantly used in computer Constantly used in computer

programmingprogramming Conditional statements can be nestedConditional statements can be nested

The The switchswitch statement easily and statement easily and elegantly checks an expression for a elegantly checks an expression for a sequence of valuessequence of values

31

Page 32: 05. Conditional Statements

QuestionsQuestions??

Conditional StatementsConditional Statements

http://academy.telerik.com

Page 33: 05. Conditional Statements

ExercisesExercises

1.1. Write an Write an ifif statement that examines two statement that examines two integer variables and exchanges their integer variables and exchanges their values if the first one is greater than the values if the first one is greater than the second one.second one.

2.2. Write a program that shows the sign of Write a program that shows the sign of the product of three real numbers the product of three real numbers without calculating it. Use a sequence of without calculating it. Use a sequence of if statements.if statements.

3.3. Write a program that finds the biggest of Write a program that finds the biggest of three integers using nested if three integers using nested if statements.statements.

4.4. Sort Sort 33 real values in descending order real values in descending order using nested if statements.using nested if statements. 33

Page 34: 05. Conditional Statements

Exercises (2)Exercises (2)

5.5. Write program that asks for a digit and Write program that asks for a digit and depending on the input shows the name depending on the input shows the name of that digit (in English) using a switch of that digit (in English) using a switch statement.statement.

6.6. Write a program that enters the Write a program that enters the coefficients coefficients aa, , bb and and cc of a quadratic of a quadratic equationequation

a*xa*x22 ++ b*xb*x ++ cc == 00

and calculates and prints its real roots. and calculates and prints its real roots. Note that quadratic equations may have Note that quadratic equations may have 00, , 11 or or 22 real roots. real roots.

Write a program that finds the greatest of Write a program that finds the greatest of given given 55 variables. variables. 34

Page 35: 05. Conditional Statements

Exercises (3)Exercises (3)

8.8. Write a program that, depending on Write a program that, depending on the user's choice inputs the user's choice inputs intint, , doubledouble or or stringstring variable. If the variable is variable. If the variable is integer or double, increases it with 1. If integer or double, increases it with 1. If the variable is string, appends "the variable is string, appends "**" at " at its end. The program must show the its end. The program must show the value of that variable as a console value of that variable as a console output. Use output. Use switchswitch statement. statement.

9.9. We are given 5 integer numbers. Write We are given 5 integer numbers. Write a program that checks if the sum of a program that checks if the sum of some subset of them is some subset of them is 00. Example: . Example: 33, , --22, , 11, , 11, , 88 1+1-2=01+1-2=0..

35

Page 36: 05. Conditional Statements

Exercises (4)Exercises (4)

10.10. Write a program that applies bonus Write a program that applies bonus scores to given scores in the range scores to given scores in the range [1..9]. The program reads a digit as an [1..9]. The program reads a digit as an input. If the digit is between 1 and 3, input. If the digit is between 1 and 3, the program multiplies it by 10; if it is the program multiplies it by 10; if it is between 4 and 6, multiplies it by 100; between 4 and 6, multiplies it by 100; if it is between 7 and 9, multiplies it by if it is between 7 and 9, multiplies it by 1000. If it is zero or if the value is not a 1000. If it is zero or if the value is not a digit, the program must report an digit, the program must report an error.error.

Use a Use a switchswitch statement and at the statement and at the end print the calculated new value in end print the calculated new value in the console.the console. 36

Page 37: 05. Conditional Statements

Exercises (5)Exercises (5)

11.11. * Write a program that converts a * Write a program that converts a number in the range [0...999] to a text number in the range [0...999] to a text corresponding to its English corresponding to its English pronunciation. Examples:pronunciation. Examples:

0 0 ""ZeroZero""

273 273 "Two hundred seventy three" "Two hundred seventy three"

400 400 "Four hundred" "Four hundred"

501 501 " "Five hundred and oneFive hundred and one""

711 711 "Severn hundred and eleven" "Severn hundred and eleven"

37