SlideShare a Scribd company logo
1 of 12
C#
LECTURE#6
Abid Kohistani.
GC Madyan Swat
Conditions and If Statements
C# supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
Conditions and If Statements Cont..
C# has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C# code to be executed if a condition is True.
Syntax:
Example:
if (condition)
{
// block of code to be executed if the condition
is True
}
int x = 20;
int y = 18;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
The else Statement
Use the else statement to specify a block of code to be executed if the condition is False.
Syntax:
Example:
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} // Outputs "Good evening."
The else if Statement
Use the else if statement to specify a new condition if the first condition is False.
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
Else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} // Outputs "Good evening."
Syntax Example
Short Hand If...Else (Ternary Operator)
ternary operator consists of three operands. It can be used to replace multiple lines of code with a single
line. It is often used to replace simple if else statements:
Syntax:
Example:
variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);
Switch Statements
Use the switch statement to select one of many code blocks to be executed. This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords will be described later in this chapter
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Syntax:
Switch Example
The example below uses the weekday
number to calculate the weekday name:
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
} // Outputs "Thursday" (day 4)
The break Keyword
When C# reaches a break keyword, it breaks out of the switch block. This will stop the execution of more
code and case testing inside the block. When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Syntax:
The default Keyword
The default keyword is optional and specifies some code to run if there is no case match:
int day = 4;
switch (day)
{
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
} // Outputs "Looking forward to the Weekend."
Syntax:
END

More Related Content

What's hot

Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphsdaimk2020
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 

What's hot (20)

Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Java
JavaJava
Java
 
VB Script
VB ScriptVB Script
VB Script
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphs
 
Python datetime
Python datetimePython datetime
Python datetime
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Data struture lab
Data struture labData struture lab
Data struture lab
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Vb script
Vb scriptVb script
Vb script
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 

Similar to Conditions In C# C-Sharp

03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statementsAbdul Samad
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro 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
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Neeru Mittal
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision ControlJayfee Ramos
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsPrabu U
 
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.pptxUjwala Junghare
 

Similar to Conditions In C# C-Sharp (20)

03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statements
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
Loops
LoopsLoops
Loops
 
csc ppt 15.pptx
csc ppt 15.pptxcsc ppt 15.pptx
csc ppt 15.pptx
 
C # (2)
C # (2)C # (2)
C # (2)
 
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
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Flow Control (C#)
Flow Control (C#)Flow Control (C#)
Flow Control (C#)
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 
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
 
Vb (2)
Vb (2)Vb (2)
Vb (2)
 

More from Abid Kohistani

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and NotationsAbid Kohistani
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Abid Kohistani
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAbid Kohistani
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.Abid Kohistani
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Abid Kohistani
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)Abid Kohistani
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)Abid Kohistani
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Abid Kohistani
 

More from Abid Kohistani (9)

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and Notations
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and Encapsulation
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 

Recently uploaded

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Conditions In C# C-Sharp

  • 2. Conditions and If Statements C# supports the usual logical conditions from mathematics: Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b Equal to a == b Not Equal to: a != b
  • 3. Conditions and If Statements Cont.. C# has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed
  • 4. The if Statement Use the if statement to specify a block of C# code to be executed if a condition is True. Syntax: Example: if (condition) { // block of code to be executed if the condition is True } int x = 20; int y = 18; if (x > y) { Console.WriteLine("x is greater than y"); }
  • 5. The else Statement Use the else statement to specify a block of code to be executed if the condition is False. Syntax: Example: if (condition) { // block of code to be executed if the condition is True } else { // block of code to be executed if the condition is False } int time = 20; if (time < 18) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } // Outputs "Good evening."
  • 6. The else if Statement Use the else if statement to specify a new condition if the first condition is False. if (condition1) { // block of code to be executed if condition1 is True } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is True } Else { // block of code to be executed if the condition1 is false and condition2 is False } int time = 22; if (time < 10) { Console.WriteLine("Good morning."); } else if (time < 20) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } // Outputs "Good evening." Syntax Example
  • 7. Short Hand If...Else (Ternary Operator) ternary operator consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements: Syntax: Example: variable = (condition) ? expressionTrue : expressionFalse; int time = 20; string result = (time < 18) ? "Good day." : "Good evening."; Console.WriteLine(result);
  • 8. Switch Statements Use the switch statement to select one of many code blocks to be executed. This is how it works: The switch expression is evaluated once The value of the expression is compared with the values of each case If there is a match, the associated block of code is executed The break and default keywords will be described later in this chapter switch(expression) { case x: // code block break; case y: // code block break; default: // code block break; } Syntax:
  • 9. Switch Example The example below uses the weekday number to calculate the weekday name: int day = 4; switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; } // Outputs "Thursday" (day 4)
  • 10. The break Keyword When C# reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing. switch(expression) { case x: // code block break; case y: // code block break; default: // code block break; } Syntax:
  • 11. The default Keyword The default keyword is optional and specifies some code to run if there is no case match: int day = 4; switch (day) { case 6: Console.WriteLine("Today is Saturday."); break; case 7: Console.WriteLine("Today is Sunday."); break; default: Console.WriteLine("Looking forward to the Weekend."); break; } // Outputs "Looking forward to the Weekend." Syntax:
  • 12. END