Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
C++ for Engineers and Scientists Third Edition
Advertisements

Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
ASP.NET MVC Course Program, Trainers, Evaluation, Exams, Resources SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
C# OOP Advanced Course Introduction SoftUni Team Technical Trainers Software University
Java OOP Advanced Course Introduction SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Repeating Code Multiple Times
Array and List Algorithms
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Presentation transcript:

Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University

2 1.Comparison and Logical Operators 2.The if Statement 3.The if-else Statement 4.Nested if Statements 5.The switch-case Statement Table of Contents

Comparison and Logical Operators

4 Operator Notation in C# Applicable for Equals== strings / numbers / dates / most objects Not Equals != Greater Than > numbers / dates / comparable objects Greater Than or Equals >= Less Than < Less Than or Equals <= Comparison Operators bool result = (5 <= 6); Console.WriteLine(result); // True  Example:

5  De Morgan laws  !!A  A  !(A || B)  !A && !B  !(A && B)  !A || !B Logical OperatorsOperator Notation in C# Example Logical NOT ! !false  true Logical AND && true && true  true Logical OR || true || false  true Logical Exclusive OR (XOR) ^ true ^ false  true

if and if-else Implementing Conditional Logic

7  The simplest conditional statement  Enables you to test for a condition  Branch to different blocks in the code depending on the result  The simplest form of the if statement: The if Statement if (condition) { statements; statements;}

8  The condition can be:  Boolean variable  Boolean logical expression  Comparison expression  The condition cannot be integer variable (like in C / C++)  The statement can be:  Single statement ending with a semicolon  Block enclosed in curly braces Condition and Statement

9  The condition is evaluated  If it is true, the statement is executed  If it is false, the statement is skipped How It Works? true condition statements false

10 The if Statement – Example static void Main() { Console.WriteLine("Enter two numbers."); Console.WriteLine("Enter two numbers."); int biggerNum = int.Parse(Console.ReadLine()); int biggerNum = int.Parse(Console.ReadLine()); int smallerNum = int.Parse(Console.ReadLine()); int smallerNum = int.Parse(Console.ReadLine()); if (smallerNum > biggerNum) if (smallerNum > biggerNum) { biggerNum = smallerNum; biggerNum = smallerNum; } Console.WriteLine("The greater number is: {0}", biggerNum); Console.WriteLine("The greater number is: {0}", biggerNum);}

The if Statement Live Demo

12  More complex and useful conditional statement  Executes one branch if the condition is true, and another if it is false  The simplest form of an if-else statement: The if-else Statement if (expression) { some_statement; some_statement;}else{ another_statement; another_statement;}

13  The condition is evaluated  If it is true, the first statement is executed  If it is false, the second statement is executed How It Works? condition firststatement true secondstatement false

14  Checking a number if it is odd or even if-else Statement – Example string s = Console.ReadLine(); int number = int.Parse(s); if (number % 2 == 0) { Console.WriteLine("This number is even."); Console.WriteLine("This number is even.");}else{ Console.WriteLine("This number is odd."); Console.WriteLine("This number is odd.");}

The if-else Statement Live Demo

Nested if Statements Creating More Complex Logic

17  if and if-else statements can be nested  Used inside one inside another  Each else corresponds to its closest preceding if Nested if Statements if (expression) { if (expression) if (expression) some_statement; some_statement; else else another_statement; another_statement;}else third_statement; third_statement;

18  Always use { … } blocks to avoid ambiguity  Even when a single statement follows  Avoid using more than three levels of nested if statements  Put the case you normally expect to process first  Then write the unusual cases  Arrange the code to make it more readable Nested if – Good Practices

19 Nested if Statements – Example if (first == second) { Console.WriteLine("These two numbers are equal."); Console.WriteLine("These two numbers are equal.");}else{ if (first > second) if (first > second) { Console.WriteLine("The first number is bigger."); Console.WriteLine("The first number is bigger."); } else else { Console.WriteLine("The second is bigger."); Console.WriteLine("The second is bigger."); }}

Nested if Statements Live Demo

21  We may need to use another if -construction in the else block  Thus else if can be used: Multiple if-else-if-else-… int ch = 'X'; if (ch == 'A' || ch == 'a') { Console.WriteLine("Vowel [ei]"); Console.WriteLine("Vowel [ei]");} else if (ch == 'E' || ch == 'e') { Console.WriteLine("Vowel [i:]"); Console.WriteLine("Vowel [i:]");} else if … else …

Multiple if-else Statements Live Demo

switch-case Performing Several Comparisons at Once

24  Selects for execution a statement from a list depending on the value of the switch expression The switch-case Statement 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;}

25 1.The expression is evaluated 2.When one of the constants specified in a case label is equal to the expression  The statement that corresponds to that case is executed 3.If no case is equal to the expression  If there is default case, it is executed  Otherwise the control is transferred to the end point of the switch statement How switch-case Works?

The switch-case Statement Live Demo

27  Variable types like string, enum and integral types can be used for switch expression  The value null is permitted as a case label constant  The keyword break exits the switch statement  "No fall through" rule  You are obligated to use break after each case  Multiple labels that correspond to the same statement are permitted Using switch : Rules

28  Multiple labels allow matching several cases and executing the same statement in more than one case Multiple Labels – Example 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("I don't know such animal!"); Console.WriteLine("I don't know such animal!"); break; break;}

Multiple Labels in a switch-case Live Demo

30  There must be a separate case for every normal situation  Put the normal case first  Put the most frequently executed cases first and the least frequently executed last  Order cases alphabetically or numerically  In default use case that cannot be reached under normal circumstances Using switch – Good Practices

31  Comparison and logical operators are used to compose logical conditions  The conditional statements if and if-else conditionally execution of blocks of code  Constantly used in computer programming  Conditional statements can be nested  The switch statement easily and elegantly checks an expression for a sequence of values Summary

? ? ? ? ? ? ? ? ? Conditional Statements

Homework Review Live Demo

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 34  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg