Conditional StatementsConditional StatementsImplementing Control Logic in C#Implementing Control Logic in C#
Svetlin NakovSvetlin NakovTelerik CorporationTelerik Corporationwww.telerik.comwww.telerik.com
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
Comparison and Comparison and Logical OperatorsLogical Operators
Comparison OperatorsComparison Operators
4
OperatorOperator Notation in C#Notation in 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
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 C#Notation in C#
Logical NOTLogical NOT !!
Logical ANDLogical AND &&&&
Logical ORLogical OR ||||
Logical Exclusive OR (XOR)Logical Exclusive OR (XOR) ^̂
5
ifif and and if-elseif-elseImplementing Conditional LogicImplementing Conditional Logic
The The ifif Statement Statement The most simple conditional statementThe most simple conditional statement Enables you to test for a conditionEnables you to test for a condition Branch to different parts of the code Branch to different parts of the code
depending on the resultdepending on the result The simplest form of an The simplest form of an ifif statement: statement:
if (condition) if (condition) {{ statements;statements;}}
7
Condition and StatementCondition and Statement The condition can be:The condition can be:
Boolean variableBoolean variable
Boolean logical expressionBoolean logical expression
Comparison expressionComparison expression The condition cannot be integer variable (like The condition cannot be integer variable (like
in C / C++)in C / C++) The statement can be:The statement can be:
Single statement ending with a semicolonSingle statement ending with a semicolon
Block enclosed in bracesBlock enclosed in braces 8
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
falsefalse
9
The The ifif Statement – Example Statement – Example
10
static void Main()static void Main(){{ Console.WriteLine("Enter two numbers.");Console.WriteLine("Enter two numbers.");
int biggerNumber = int.Parse(Console.ReadLine());int biggerNumber = int.Parse(Console.ReadLine()); int smallerNumber = int.Parse(Console.ReadLine());int smallerNumber = 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);}}
The The ifif Statement StatementLive DemoLive Demo
The The if-elseif-else StatementStatement
More complex and useful conditional statementMore complex and useful conditional statement
Executes one branch if the condition is true, and Executes one branch if the condition is true, and another if it is false 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
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 executedIf it is false, the second statement is executed
conditioncondition
firstfirststatementstatement
truetrue
secondsecondstatementstatement
falsefalse
13
if-elseif-else Statement – ExampleStatement – Example Checking a number if it is odd or evenChecking a number if it is odd or even
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
The The if-elseif-else Statement StatementLive DemoLive Demo
Nested Nested ifif Statements Statements Creating More Complex LogicCreating More Complex Logic
Nested Nested ifif Statements Statements ifif and and if-elseif-else statements can be statements can be nestednested, i.e. used , i.e. used
inside another inside another ifif or or elseelse statementstatement
Every Every elseelse corresponds to its closest preceding corresponds to its closest preceding ifif
if (expression) if (expression) {{ if (expression) if (expression) {{ statement;statement; }} else else {{ statement;statement; }}}}elseelse statement; statement;
17
Nested Nested ifif – Good Practices – Good Practices
Always use Always use {{ …… }} blocks to avoid ambiguity blocks to avoid ambiguity
Even when a single statement followsEven when a single statement follows
Avoid using more than three levels of nested Avoid using more than three levels of nested ifif statementsstatements
Put the case you normally expect to process Put the case you normally expect to process first, then write the unusual casesfirst, then write the unusual cases
Arrange the code to make it more readableArrange the code to make it more readable
18
Nested Nested ifif Statements – Example Statements – Exampleif (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
Nested Nested ififStatementsStatements
Live DemoLive Demo
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 …
Multiple Multiple if-elseif-elseStatementsStatements
Live DemoLive Demo
switch-caseswitch-caseMaking Several Comparisons at OnceMaking Several Comparisons at Once
The The switch-caseswitch-case Statement Statement Selects for execution a statement from a list Selects for execution a statement from a list
depending on the value of the depending on the value of 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
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 a case When one of the constants specified in a case label is equal to the expressionlabel is equal to the expression
The statement that corresponds to that case The statement that corresponds to that case is executedis 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 the Otherwise the control is transferred to the end point of the switch statement end point of the switch statement
25
The The switch-case switch-case StatementStatement
Live DemoLive Demo
Using Using switchswitch: Rules: Rules Variables types like Variables types like stringstring, , enumenum and integral and integral
types can be used for types can be used for switchswitch expressionexpression
The value The value nullnull is permitted as a case label is permitted as a case label constantconstant
The keyword The keyword breakbreak exits the switch statement exits the switch statement
"No fall through" rule – you are obligated to use "No fall through" rule – you are obligated to use breakbreak after each case after each case
Multiple labels that correspond to the same Multiple labels that correspond to the same statement are permittedstatement are permitted
27
Multiple Labels – ExampleMultiple Labels – Example
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 animal!"); Console.WriteLine("There is no such animal!"); break;break;}}
You can use multiple labels to execute the same You can use multiple labels to execute the same statement in more than one casestatement in more than one case
28
Multiple Labels in Multiple Labels in a a switch-caseswitch-case
Live DemoLive Demo
Using Using switchswitch – Good Practices – Good Practices
There must be a separate There must be a separate casecase for every for every normal situationnormal situation
Put the normal case firstPut the normal case first
Put the most frequently executed cases first Put the most frequently executed cases first and the least frequently executed lastand the least frequently executed last
Order cases alphabetically or numericallyOrder cases alphabetically or numerically In In defaultdefault use case that cannot be reached use case that cannot be reached
under normalunder normal circumstancescircumstances
30
SummarySummary Comparison and logical operators are used to Comparison and logical operators are used to
compose logical conditionscompose logical conditions The conditional statements The conditional statements ifif and and if-elseif-else
provide conditional execution of blocks of codeprovide conditional execution of blocks of code
Constantly used in computer programmingConstantly used in computer programming
Conditional statements can be nestedConditional statements can be nested
The The switchswitch statement easily and elegantly statement easily and elegantly checks an expression for a sequence of valueschecks an expression for a sequence of values
31
Questions?Questions?
Conditional StatementsConditional Statements
http://academy.telerik.com
ExercisesExercises
1.1. Write an Write an ifif statement that examines two integer statement that examines two integer variables and exchanges their values if the first one variables and exchanges their values if the first one is greater than the second one.is greater than the second one.
2.2. Write a program that shows the sign of the product Write a program that shows the sign of the product of three real numbers without calculating it. Use a of three real numbers without calculating it. Use a sequence of if statements.sequence of if statements.
3.3. Write a program that finds the biggest of three Write a program that finds the biggest of three integers using nested if statements.integers using nested if statements.
4.4. Sort Sort 33 real values in descending order using nested if real values in descending order using nested if statements.statements.
33
Exercises (2)Exercises (2)
1.1. Write program that asks for a digit and depending Write program that asks for a digit and depending on the input shows the name of that digit (in on the input shows the name of that digit (in English) using a switch statement.English) using a switch statement.
2.2. Write a program that enters the coefficients Write a program that enters the coefficients aa, , bb and and cc of a quadratic equation of a quadratic equation
a*xa*x22 ++ b*xb*x ++ cc == 00
and calculates and prints its real roots. Note that and calculates and prints its real roots. Note that quadratic equations may have quadratic equations may have 00, , 11 or or 22 real roots. real roots.
5.5. Write a program that finds the greatest of given Write a program that finds the greatest of given 55 variables.variables.
34
Exercises (3)Exercises (3)
1.1. Write a program that, depending on the user's Write a program that, depending on the user's choice inputs choice inputs intint, , doubledouble or or stringstring variable. If the variable. If the variable is integer or double, increases it with 1. If variable is integer or double, increases it with 1. If the variable is string, appends "the variable is string, appends "**" at its end. The " at its end. The program must show the value of that variable as a program must show the value of that variable as a console output. Use console output. Use switchswitch statement. statement.
2.2. We are given 5 integer numbers. Write a program We are given 5 integer numbers. Write a program that checks if the sum of some subset of them is that checks if the sum of some subset of them is 00. . Example: Example: 33, , -2-2, , 11, , 11, , 88 1+1-2=01+1-2=0..
35
Exercises (4)Exercises (4)
1.1. Write a program that applies bonus scores to given Write a program that applies bonus scores to given scores in the range [1..9]. The program reads a digit scores in the range [1..9]. The program reads a digit as an input. If the digit is between 1 and 3, the as an input. If the digit is between 1 and 3, the program multiplies it by 10; if it is between 4 and 6, program multiplies it by 10; if it is between 4 and 6, multiplies it by 100; if it is between 7 and 9, multiplies it by 100; if it is between 7 and 9, multiplies it by 1000. If it is zero or if the value is not multiplies it by 1000. If it is zero or if the value is not a digit, the program must report an error.a digit, the program must report an error.
Use a Use a switchswitch statement and at the end print the statement and at the end print the calculated new value in the console.calculated new value in the console.
36
Exercises (5)Exercises (5)
1.1. * Write a program that converts a number in the * Write a program that converts a number in the range [0...999] to a text corresponding to its range [0...999] to a text corresponding to its English pronunciation. Examples:English 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