SlideShare a Scribd company logo
Conditional StatementsConditional Statements
Implementing Control Logic in C#Implementing Control Logic in C#
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. Comparison and Logical OperatorsComparison and Logical Operators
2.2. TheThe ifif StatementStatement
3.3. TheThe if-elseif-else StatementStatement
4.4. NestedNested ifif StatementsStatements
5.5. TheThe switch-caseswitch-case StatementStatement
2
Comparison andComparison 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  AA
!(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 andand if-elseif-else
Implementing Conditional LogicImplementing Conditional Logic
TheThe ifif StatementStatement
 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 codeBranch to different parts of the code
depending on the resultdepending on the result
 The simplest form of anThe 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 (likeThe 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 skippedIf it is false, the statement is skipped
truetrue
conditioncondition
statementstatement
falsefalse
9
TheThe ifif Statement – ExampleStatement – 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);
}}
TheThe ifif StatementStatement
Live DemoLive Demo
TheThe if-elseif-else StatementStatement
 More complex and useful conditional statementMore complex and useful conditional statement
 Executes one branch if the condition is true, andExecutes one branch if the condition is true, and
another if it is falseanother if it is false
 The simplest form of anThe simplest form of an if-elseif-else statement:statement:
if (expression)if (expression)
{{
statement1;statement1;
}}
elseelse
{{
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
firstfirst
statementstatement
truetrue
secondsecond
statementstatement
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
TheThe if-elseif-else StatementStatement
Live DemoLive Demo
NestedNested ifif StatementsStatements
Creating More Complex LogicCreating More Complex Logic
NestedNested ifif StatementsStatements
 ifif andand if-elseif-else statements can bestatements can be nestednested, i.e. used, i.e. used
inside anotherinside another ifif oror elseelse statementstatement
 EveryEvery elseelse corresponds to its closest precedingcorresponds to its closest preceding ifif
if (expression)if (expression)
{{
if (expression)if (expression)
{{
statement;statement;
}}
elseelse
{{
statement;statement;
}}
}}
elseelse
statement;statement;
17
NestedNested ifif – Good Practices– Good Practices
 Always useAlways use {{ …… }} blocks to avoid ambiguityblocks to avoid ambiguity
Even when a single statement followsEven when a single statement follows
 Avoid using more than three levels of nestedAvoid using more than three levels of nested
ifif statementsstatements
 Put the case you normally expect to processPut 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
NestedNested ifif Statements – ExampleStatements – Example
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
NestedNested ifif
StatementsStatements
Live DemoLive Demo
Multiple if-else-if-else-…Multiple if-else-if-else-…
 Sometimes we need to use anotherSometimes we need to use another ifif--
construction in theconstruction in the elseelse blockblock
ThusThus 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 …
MultipleMultiple if-elseif-else
StatementsStatements
Live DemoLive Demo
switch-caseswitch-case
Making Several Comparisons at OnceMaking Several Comparisons at Once
TheThe switch-caseswitch-case StatementStatement
 Selects for execution a statement from a listSelects for execution a statement from a list
depending on the value of thedepending on the value of the switchswitch
expressionexpression
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
HowHow switch-caseswitch-case Works?Works?
1.1. The expression is evaluatedThe expression is evaluated
2.2. When one of the constants specified in a caseWhen 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 caseThe statement that corresponds to that case
is executedis executed
1.1. 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 theOtherwise the control is transferred to the
end point of the switch statementend point of the switch statement
25
TheThe switch-caseswitch-case
StatementStatement
Live DemoLive Demo
UsingUsing switchswitch: Rules: Rules
 Variables types likeVariables types like stringstring,, enumenum and integraland integral
types can be used fortypes can be used for switchswitch expressionexpression
 The valueThe value nullnull is permitted as a case labelis permitted as a case label
constantconstant
 The keywordThe keyword breakbreak exits the switch statementexits the switch statement
 "No fall through" rule – you are obligated to use"No fall through" rule – you are obligated to use
breakbreak after each caseafter each case
 Multiple labels that correspond to the sameMultiple 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 sameYou can use multiple labels to execute the same
statement in more than one casestatement in more than one case
28
Multiple Labels inMultiple Labels in
aa switch-caseswitch-case
Live DemoLive Demo
UsingUsing switchswitch – Good Practices– Good Practices
 There must be a separateThere must be a separate casecase for everyfor every
normal situationnormal situation
 Put the normal case firstPut the normal case first
Put the most frequently executed cases firstPut 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
 InIn defaultdefault use case that cannot be reacheduse case that cannot be reached
under normalunder normal circumstancescircumstances
30
SummarySummary
 Comparison and logical operators are used toComparison and logical operators are used to
compose logical conditionscompose logical conditions
 The conditional statementsThe conditional statements ifif andand 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
 TheThe switchswitch statement easily and elegantlystatement 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 anWrite an ifif statement that examines two integerstatement that examines two integer
variables and exchanges their values if the first onevariables 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 productWrite a program that shows the sign of the product
of three real numbers without calculating it. Use aof 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 threeWrite a program that finds the biggest of three
integers using nested if statements.integers using nested if statements.
4.4. SortSort 33 real values in descending order using nested ifreal values in descending order using nested if
statements.statements.
33
Exercises (2)Exercises (2)
5.5. Write program that asks for a digit and dependingWrite program that asks for a digit and depending
on the input shows the name of that digit (inon the input shows the name of that digit (in
English) using a switch statement.English) using a switch statement.
6.6. Write a program that enters the coefficientsWrite a program that enters the coefficients aa,, bb andand
cc of a quadratic equationof a quadratic equation
a*xa*x22
++ b*xb*x ++ cc == 00
and calculates and prints its real roots. Note thatand calculates and prints its real roots. Note that
quadratic equations may havequadratic equations may have 00,, 11 oror 22 real roots.real roots.
 Write a program that finds the greatest of givenWrite a program that finds the greatest of given 55
variables.variables.
34
Exercises (3)Exercises (3)
8.8. Write a program that, depending on the user'sWrite a program that, depending on the user's
choice inputschoice inputs intint,, doubledouble oror stringstring variable. If thevariable. If the
variable is integer or double, increases it with 1. Ifvariable 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 aprogram must show the value of that variable as a
console output. Useconsole output. Use switchswitch statement.statement.
9.9. We are given 5 integer numbers. Write a programWe are given 5 integer numbers. Write a program
that checks if the sum of some subset of them isthat 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)
10.10. Write a program that applies bonus scores to givenWrite a program that applies bonus scores to given
scores in the range [1..9]. The program reads a digitscores in the range [1..9]. The program reads a digit
as an input. If the digit is between 1 and 3, theas 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 notmultiplies 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 aUse a switchswitch statement and at the end print thestatement and at the end print the
calculated new value in the console.calculated new value in the console.
36
Exercises (5)Exercises (5)
11.11. * 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 itsrange [0...999] to a text corresponding to its
English pronunciation. Examples:English pronunciation. Examples:
00  ""ZeroZero""
273273  "Two hundred seventy three""Two hundred seventy three"
400400  "Four hundred""Four hundred"
501501  ""Five hundred and oneFive hundred and one""
711711  "Severn hundred and eleven""Severn hundred and eleven"
37

More Related Content

What's hot

C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
Haard Shah
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
rajshreemuthiah
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
Abid Kohistani
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
RAJ KUMAR
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinarurumedina
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
TANUJ ⠀
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
tanmaymodi4
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
Techglyphs
 
Control structures i
Control structures i Control structures i
Control structures i
Ahmad Idrees
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
Way2itech
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
Explore Skilled
 
If-else and switch-case
If-else and switch-caseIf-else and switch-case
If-else and switch-case
Manash Kumar Mondal
 
Nesting of if else statement & Else If Ladder
Nesting of if else statement & Else If Ladder Nesting of if else statement & Else If Ladder
Nesting of if else statement & Else If Ladder
Vishvesh Jasani
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
Siddique Ibrahim
 

What's hot (20)

C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medina
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
 
M C6java5
M C6java5M C6java5
M C6java5
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Control structures i
Control structures i Control structures i
Control structures i
 
7 decision-control
7 decision-control7 decision-control
7 decision-control
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
If-else and switch-case
If-else and switch-caseIf-else and switch-case
If-else and switch-case
 
Nesting of if else statement & Else If Ladder
Nesting of if else statement & Else If Ladder Nesting of if else statement & Else If Ladder
Nesting of if else statement & Else If Ladder
 
M C6java6
M C6java6M C6java6
M C6java6
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 

Viewers also liked

Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04IIUM
 
Conditional Sentence
Conditional SentenceConditional Sentence
Conditional Sentence
Parves Sikder
 
Data mining assignment 4
Data mining assignment 4Data mining assignment 4
Data mining assignment 4
BarryK88
 
Data mining assignment 5
Data mining assignment 5Data mining assignment 5
Data mining assignment 5
BarryK88
 
Tree pruning
Tree pruningTree pruning
Tree pruning
priya_kalia
 
01 10 speech channel assignment
01 10 speech channel assignment01 10 speech channel assignment
01 10 speech channel assignmentEricsson Saudi
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
Platonov Sergey
 
Data mining assignment 1
Data mining assignment 1Data mining assignment 1
Data mining assignment 1
BarryK88
 
Data Engineering - Data Mining Assignment
Data Engineering - Data Mining AssignmentData Engineering - Data Mining Assignment
Data Engineering - Data Mining AssignmentDarran Mottershead
 
4.2 bst
4.2 bst4.2 bst
4.2 bst
Krish_ver2
 
Data Mining – analyse Bank Marketing Data Set
Data Mining – analyse Bank Marketing Data SetData Mining – analyse Bank Marketing Data Set
Data Mining – analyse Bank Marketing Data SetMateusz Brzoska
 
DATA MINING on WEKA
DATA MINING on WEKADATA MINING on WEKA
DATA MINING on WEKAsatyamkhatri
 
Grammar Conditional sentence type 2 and 3
Grammar Conditional sentence type 2 and 3Grammar Conditional sentence type 2 and 3
Grammar Conditional sentence type 2 and 3Kurniapeni Rahayu
 
Third Conditional grammar explanation
Third Conditional grammar explanationThird Conditional grammar explanation
Third Conditional grammar explanationAngel Ingenio
 
Data ming wsn
Data ming wsnData ming wsn
Data ming wsn
Mesbah-Ul Islam
 
Conditional sentences grammar
Conditional sentences  grammarConditional sentences  grammar
Conditional sentences grammarantaresian
 

Viewers also liked (20)

Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04
 
Conditional Sentence
Conditional SentenceConditional Sentence
Conditional Sentence
 
Data mining assignment 4
Data mining assignment 4Data mining assignment 4
Data mining assignment 4
 
Data mining assignment 5
Data mining assignment 5Data mining assignment 5
Data mining assignment 5
 
Tree pruning
Tree pruningTree pruning
Tree pruning
 
01 10 speech channel assignment
01 10 speech channel assignment01 10 speech channel assignment
01 10 speech channel assignment
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
Data mining assignment 1
Data mining assignment 1Data mining assignment 1
Data mining assignment 1
 
Data Engineering - Data Mining Assignment
Data Engineering - Data Mining AssignmentData Engineering - Data Mining Assignment
Data Engineering - Data Mining Assignment
 
Data mining notes
Data mining notesData mining notes
Data mining notes
 
4.2 bst
4.2 bst4.2 bst
4.2 bst
 
Data Mining – analyse Bank Marketing Data Set
Data Mining – analyse Bank Marketing Data SetData Mining – analyse Bank Marketing Data Set
Data Mining – analyse Bank Marketing Data Set
 
DATA MINING on WEKA
DATA MINING on WEKADATA MINING on WEKA
DATA MINING on WEKA
 
Ch06
Ch06Ch06
Ch06
 
Grammar Conditional sentence type 2 and 3
Grammar Conditional sentence type 2 and 3Grammar Conditional sentence type 2 and 3
Grammar Conditional sentence type 2 and 3
 
Decision trees
Decision treesDecision trees
Decision trees
 
Third Conditional grammar explanation
Third Conditional grammar explanationThird Conditional grammar explanation
Third Conditional grammar explanation
 
Naive bayes
Naive bayesNaive bayes
Naive bayes
 
Data ming wsn
Data ming wsnData ming wsn
Data ming wsn
 
Conditional sentences grammar
Conditional sentences  grammarConditional sentences  grammar
Conditional sentences grammar
 

Similar to 05 Conditional statements

05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
Intro C# Book
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
Saad Sheikh
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
Jyoti Bhardwaj
 
Unit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptxUnit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptx
Ujwala Junghare
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
SHRIRANG PINJARKAR
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
chintupro9
 
loops.pdf
loops.pdfloops.pdf
loops.pdf
AmayJaiswal4
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
RaginiJain21
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
Ahmad Idrees
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NET
Ujwala Junghare
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
Loops
LoopsLoops
Loops
Kamran
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
Mehul Desai
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
nmahi96
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
Anil Dutt
 

Similar to 05 Conditional statements (20)

05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
Unit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptxUnit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptx
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
loops.pdf
loops.pdfloops.pdf
loops.pdf
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NET
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Loops
LoopsLoops
Loops
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 

More from maznabili

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
maznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
maznabili
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
maznabili
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
maznabili
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
maznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
maznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
15 Text files
15 Text files15 Text files
15 Text files
maznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
maznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
maznabili
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
maznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
maznabili
 
09 Methods
09 Methods09 Methods
09 Methods
maznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
maznabili
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
06 Loops
06 Loops06 Loops
06 Loops
maznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
maznabili
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
maznabili
 

More from maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 

05 Conditional statements

  • 1. Conditional StatementsConditional Statements Implementing Control Logic in C#Implementing Control Logic in C# Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents 1.1. Comparison and Logical OperatorsComparison and Logical Operators 2.2. TheThe ifif StatementStatement 3.3. TheThe if-elseif-else StatementStatement 4.4. NestedNested ifif StatementsStatements 5.5. TheThe switch-caseswitch-case StatementStatement 2
  • 3. Comparison andComparison and Logical OperatorsLogical Operators
  • 4. 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
  • 5. Logical OperatorsLogical Operators  De Morgan lawsDe Morgan laws !!A!!A  AA !(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
  • 6. ifif andand if-elseif-else Implementing Conditional LogicImplementing Conditional Logic
  • 7. TheThe ifif StatementStatement  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 codeBranch to different parts of the code depending on the resultdepending on the result  The simplest form of anThe simplest form of an ifif statement:statement: if (condition)if (condition) {{ statements;statements; }} 7
  • 8. 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 (likeThe 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
  • 9. 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 skippedIf it is false, the statement is skipped truetrue conditioncondition statementstatement falsefalse 9
  • 10. TheThe ifif Statement – ExampleStatement – 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); }}
  • 12. TheThe if-elseif-else StatementStatement  More complex and useful conditional statementMore complex and useful conditional statement  Executes one branch if the condition is true, andExecutes one branch if the condition is true, and another if it is falseanother if it is false  The simplest form of anThe simplest form of an if-elseif-else statement:statement: if (expression)if (expression) {{ statement1;statement1; }} elseelse {{ statement2;statement2; }} 12
  • 13. 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 firstfirst statementstatement truetrue secondsecond statementstatement falsefalse 13
  • 14. 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
  • 16. NestedNested ifif StatementsStatements Creating More Complex LogicCreating More Complex Logic
  • 17. NestedNested ifif StatementsStatements  ifif andand if-elseif-else statements can bestatements can be nestednested, i.e. used, i.e. used inside anotherinside another ifif oror elseelse statementstatement  EveryEvery elseelse corresponds to its closest precedingcorresponds to its closest preceding ifif if (expression)if (expression) {{ if (expression)if (expression) {{ statement;statement; }} elseelse {{ statement;statement; }} }} elseelse statement;statement; 17
  • 18. NestedNested ifif – Good Practices– Good Practices  Always useAlways use {{ …… }} blocks to avoid ambiguityblocks to avoid ambiguity Even when a single statement followsEven when a single statement follows  Avoid using more than three levels of nestedAvoid using more than three levels of nested ifif statementsstatements  Put the case you normally expect to processPut 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
  • 19. NestedNested ifif Statements – ExampleStatements – Example 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
  • 21. Multiple if-else-if-else-…Multiple if-else-if-else-…  Sometimes we need to use anotherSometimes we need to use another ifif-- construction in theconstruction in the elseelse blockblock ThusThus 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 …
  • 23. switch-caseswitch-case Making Several Comparisons at OnceMaking Several Comparisons at Once
  • 24. TheThe switch-caseswitch-case StatementStatement  Selects for execution a statement from a listSelects for execution a statement from a list depending on the value of thedepending on the value of the switchswitch expressionexpression 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
  • 25. HowHow switch-caseswitch-case Works?Works? 1.1. The expression is evaluatedThe expression is evaluated 2.2. When one of the constants specified in a caseWhen 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 caseThe statement that corresponds to that case is executedis executed 1.1. 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 theOtherwise the control is transferred to the end point of the switch statementend point of the switch statement 25
  • 27. UsingUsing switchswitch: Rules: Rules  Variables types likeVariables types like stringstring,, enumenum and integraland integral types can be used fortypes can be used for switchswitch expressionexpression  The valueThe value nullnull is permitted as a case labelis permitted as a case label constantconstant  The keywordThe keyword breakbreak exits the switch statementexits the switch statement  "No fall through" rule – you are obligated to use"No fall through" rule – you are obligated to use breakbreak after each caseafter each case  Multiple labels that correspond to the sameMultiple labels that correspond to the same statement are permittedstatement are permitted 27
  • 28. 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 sameYou can use multiple labels to execute the same statement in more than one casestatement in more than one case 28
  • 29. Multiple Labels inMultiple Labels in aa switch-caseswitch-case Live DemoLive Demo
  • 30. UsingUsing switchswitch – Good Practices– Good Practices  There must be a separateThere must be a separate casecase for everyfor every normal situationnormal situation  Put the normal case firstPut the normal case first Put the most frequently executed cases firstPut 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  InIn defaultdefault use case that cannot be reacheduse case that cannot be reached under normalunder normal circumstancescircumstances 30
  • 31. SummarySummary  Comparison and logical operators are used toComparison and logical operators are used to compose logical conditionscompose logical conditions  The conditional statementsThe conditional statements ifif andand 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  TheThe switchswitch statement easily and elegantlystatement easily and elegantly checks an expression for a sequence of valueschecks an expression for a sequence of values 31
  • 33. ExercisesExercises 1.1. Write anWrite an ifif statement that examines two integerstatement that examines two integer variables and exchanges their values if the first onevariables 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 productWrite a program that shows the sign of the product of three real numbers without calculating it. Use aof 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 threeWrite a program that finds the biggest of three integers using nested if statements.integers using nested if statements. 4.4. SortSort 33 real values in descending order using nested ifreal values in descending order using nested if statements.statements. 33
  • 34. Exercises (2)Exercises (2) 5.5. Write program that asks for a digit and dependingWrite program that asks for a digit and depending on the input shows the name of that digit (inon the input shows the name of that digit (in English) using a switch statement.English) using a switch statement. 6.6. Write a program that enters the coefficientsWrite a program that enters the coefficients aa,, bb andand cc of a quadratic equationof a quadratic equation a*xa*x22 ++ b*xb*x ++ cc == 00 and calculates and prints its real roots. Note thatand calculates and prints its real roots. Note that quadratic equations may havequadratic equations may have 00,, 11 oror 22 real roots.real roots.  Write a program that finds the greatest of givenWrite a program that finds the greatest of given 55 variables.variables. 34
  • 35. Exercises (3)Exercises (3) 8.8. Write a program that, depending on the user'sWrite a program that, depending on the user's choice inputschoice inputs intint,, doubledouble oror stringstring variable. If thevariable. If the variable is integer or double, increases it with 1. Ifvariable 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 aprogram must show the value of that variable as a console output. Useconsole output. Use switchswitch statement.statement. 9.9. We are given 5 integer numbers. Write a programWe are given 5 integer numbers. Write a program that checks if the sum of some subset of them isthat 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
  • 36. Exercises (4)Exercises (4) 10.10. Write a program that applies bonus scores to givenWrite a program that applies bonus scores to given scores in the range [1..9]. The program reads a digitscores in the range [1..9]. The program reads a digit as an input. If the digit is between 1 and 3, theas 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 notmultiplies 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 aUse a switchswitch statement and at the end print thestatement and at the end print the calculated new value in the console.calculated new value in the console. 36
  • 37. Exercises (5)Exercises (5) 11.11. * 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 itsrange [0...999] to a text corresponding to its English pronunciation. Examples:English pronunciation. Examples: 00  ""ZeroZero"" 273273  "Two hundred seventy three""Two hundred seventy three" 400400  "Four hundred""Four hundred" 501501  ""Five hundred and oneFive hundred and one"" 711711  "Severn hundred and eleven""Severn hundred and eleven" 37