 Branching  Boolean logic  If statements  Switch statements  The evil goto statement.

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Conditional Statement
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming Fifth Edition Chapter 5 Making Decisions.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Making Decisions in c. 1.if statement Imagine that you could translate a statement such as “If it is not raining, then I will go swimming” into the C.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 4 Making Decisions.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
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.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Control Structures – Selection
Relational & Logical Operators
Relational and Logical Operators
Relational and Logical Operators
Chapter 7 Conditional Statements
Relational and Logical Operators
Boolean Expressions to Make Comparisons
Relational and Logical Operators
Relational and Logical Operators
Chap 7. Advanced Control Statements in Java
Relational and Logical Operators
Controlling Program Flow
Presentation transcript:

 Branching  Boolean logic  If statements  Switch statements  The evil goto statement

 Branching allows a program to make decisions based on some condition  If its raining, carry an umbrella  If height is greater than 6' do not permit entry  If x < 0 print an error message  Conditions are written as Boolean expressions  That evaluate to true or false

 An if-else statement chooses between two alternatives  Based on the value of a condition  If the condition is true the statement(s) following the if keyword are executed  Otherwise the statement(s) following the else keyword are executed  An else statement is not required

if (range > 100){ direction = evade(); } else { speed = accelerate(); } Let’s assume that a program is controlling a missile, if the missile far away from the target it will attempt to evade any countermeasures, otherwise it will accelerate We are assuming the range, direction and speed variables have been declared, and that the accelerate and evade functions have been defined

if (range > 100) direction = evade(); else speed = accelerate(); If the body of the if statement (the code that executes based on the condition) is only one line long then it does not need to be enclosed in {} s This is OK but, be careful if you modify your code at a later date

if (range > 100) direction = evade(); else speed = accelerate(); explode(); Consider another version of the previous example The indentation here is misleading, in fact the missile will explode regardless of its range to the target. As there are no {}s the bodies of the if and else statements only consist of the one line immediately following the condition This time, when the missile is close to the target it should accelerate and then explode, using a modified version of the previous example oops!

CConditions in if statements should be Boolean expressions UUsually two operands compared using a comparison operator OOne of ==, !=, <, >, <=, >= OOperators with two symbols (e.g. ==, <=) should not have spaces between the symbols MMake sure that you use = = and not = as the test for equality

 Born Nov. 2, 1815  Lincoln, England  Died Dec. 8, 1864  Ballintemple, Ireland  Boole approached logic by reducing it to algebra 

Opera tor MeaningExampleResult > greater than 4 > 4 False < less than 'a' < 'p' True >= greater than or equal to 4 >= 4 True <= less than or equal to 2.3 <= 2.2 False == equal to 4/3 == 1 True != not equal to 4.0/3 != 1 True

 In C the values true and false are represented by 1 (true) and 0 (false)  In a Boolean expression any non-zero value is converted to true ▪ So -16, 23, 37 would all be converted to true  The C99 standard includes a _Bool type  That only stores the values 1 or 0  Note that the Visual Studio C compiler is not C99 compliant and does not recognize the _Bool type

 A Boolean expression is an expression that evaluates to true or false  That is, to the value 0 (false) and 1 true  Therefore a condition in an if statement may consist of a single value  Or a function call that returns an integer variable  e.g. if (isOldEnough(age)) { …} ▪ Where isOldEnough is a function that returns either 1 (true) or 0 (false) based on the value of the given age

 Multiple comparisons can be combined  Using logical operators  These operators allow us to express decisions with more than one condition  AND, && in C ▪ True only if both comparisons are true  OR, || in C ▪ True if either comparison is true  NOT, ! in C, negates a Boolean expression

112 < 13 ttrue (1) 221 == 17 ffalse (0) 223 != 21 ttrue (1) 99 >= 8 ttrue (1) 112 < 13 && 7 > 7 ffalse (0) 112 < 13 || 7 > 7 ttrue (1) !!(12 < 13) && 7 > 7 ffalse (0) !! has precedence over && --16 || 23 && 0 ttrue (1) &&& has precedence over ||

 Boolean expressions can be evaluated in truth tables  The symbol  represents and  The symbol  represents or  The symbol  represents notpq pqpqpqpq pqpqpqpq  p p p p  pq pq pq pq  pq pq pq pq TTTTFFT TFFTFFF FTFTTTT FFFFTFT e.g. !(12 7 p p q q

Operator (from high to low)Associativity [], (function), post++, post--left to right ++pre, --pre, !, * (dereference), &, unary - +right to left *, /, %left to right +, -left to right >left to right, =left to right ==, !=left to right &&left to right ||left to right ? : (conditional operator)right to left =, +=, -=, *=, /=, %=right to left, (comma operator)left to right

 Brackets can be used to give operations precedence  Binary operators with the same precedence are mostly evaluated left to right  Unary operators and assignments with the same precedence are evaluated right to left  Note that x++ is evaluated before many other operations  But some of its effects occur later

if (++x > y || x > z && x > 13){ printf("Hippopotamus!"); } else { printf("Aardvark!"); } If x = 9, y = 9, and z = 3 what does this print? Prints Hippopotamus! because the ++ has precedence over everything (making x equal to 10) and && has precedence over || true false

 There are two very simple ways to avoid mistakes relating to precedence  Use brackets to avoid ambiguity  Change complex statements into multiple simpler statements  And one more piece of advice, be careful about type conversions

// Function to return true if age is 19 to 60 _Bool checkAge(int age){ if (18 < age < 61){ return 1; } else { return 0; } This logical (not C) statement: 0 < x < 100 is true if x is between 0 and 100. There is no shorthand equivalent in C, however such an expression is legal... This always returns true! Think of the condition as ((18 < age) < 61) If age is 12 then (18 < age) is false, so now evaluate: false < 61 false is cast to the an int value of 0, and when we evaluate 0 < 61 we get true Except that it doesn't work correctly! oops!

 Where two expressions are joined by && or || C performs short circuit evaluation  It may be possible to determine the result of the entire expression from the first expression  If so, the second expression is not evaluated ▪ e.g. (age > 19 && age < 61) ▪ If age is 17 there is no point in checking to see if age is < 61 as the entire expression must be false

int password; printf("Enter your password Mr. President: "); if(password = ){ printf("You may now commence nuclear war"); }else{ printf("INTRUDER ALERT!"); } One of the philosophies underlying C is that it will not perform checks to see if what you are doing is sensible (because such checks reduce efficiency) Here password is assigned the value of , and then the condition is evaluated It uses the value of attempts (now ), which evaluates to true! oops! oops! Enter your password Mr. President: 91 You may now commence nuclear war Enter your password Mr. President: 91 You may now commence nuclear war output:

 An if-else statement chooses between just two alternatives  It is often useful to allow more than two alternatives  This can be achieved in a number of ways ▪ Multiple if-else statements ▪ Nested if-else statements ▪ If - else if – else statement ▪ Switch statements

 Write a function to return the letter grade of a student given the numeric grade  Following this grade scheme* ▪ 0 – 49 fail ▪ 50 – 59 D ▪ 60 – 74 C ▪ 75 – 89 B ▪ 90+ A  *Not the grade scheme used in this class

// Function to return a letter grade char letterGrade(int grade){ if (grade > 50) return 'D'; if (grade > 59) return 'C'; if (grade > 74) return 'B'; if (grade > 89) return 'A'; else //(grade < 50) return 'F'; } It usually returns the wrong grade Remember that a function terminates as soon as a return statement is reached If grade is 81 then it is also over 50 so ‘D’ is returned The function contains 4 separate if statements, one with an else clause

// Function to return a letter grade char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50) letterGrade = 'D'; if (grade > 59) letterGrade = 'C'; if (grade > 74) letterGrade = 'B'; if (grade > 89) letterGrade = 'A'; return letterGrade; } It returns the correct grade The function contains 4 separate if statements, none with an else clause It makes 4 comparisons before returning the letter grade

lg = 'F' gr > 50 true lg = 'D' false char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50) letterGrade = 'D'; if (grade > 59) letterGrade = 'C'; if (grade > 74) letterGrade = 'B'; if (grade > 89) letterGrade = 'A'; return letterGrade; } char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50) letterGrade = 'D'; if (grade > 59) letterGrade = 'C'; if (grade > 74) letterGrade = 'B'; if (grade > 89) letterGrade = 'A'; return letterGrade; } gr > 59 true lg = 'C' false gr > 74 true lg = 'B' false gr > 89 true lg = 'A' false return lg return lg

// Function to return a letter grade char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50){ letterGrade = 'D'; if (grade > 59){ letterGrade = 'C'; if (grade > 74){ letterGrade = 'B'; if (grade > 89){ letterGrade = 'A'; }} return letterGrade; } If grade is 45 only one comparison would be made This version is similar to the previous one except that the if statements are nested within each other

lg = 'F' gr > 50 lg = 'D' true char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50){ letterGrade = 'D'; if (grade > 59){ letterGrade = 'C'; if (grade > 74){ letterGrade = 'B'; if (grade > 89){ letterGrade = 'A'; } } } } return letterGrade; } char letterGrade(int grade){ char letterGrade = 'F'; if (grade > 50){ letterGrade = 'D'; if (grade > 59){ letterGrade = 'C'; if (grade > 74){ letterGrade = 'B'; if (grade > 89){ letterGrade = 'A'; } } } } return letterGrade; } gr > 59 lg = 'C return lg return lg gr > 74 lg = 'B' true gr > 89 lg = 'A' true false

// Function to return a letter grade char letterGrade(int grade){ char letterGrade; if (grade > 50) letterGrade = 'D'; else if (grade > 59) letterGrade = 'C'; else if (grade > 74) letterGrade = 'B'; else if (grade > 89) letterGrade = 'A'; else // (grade < 50) letterGrade = 'F'; return letterGrade; } So this only ever returns D or F! In an if – else if – else statement only the body of the first true condition is evaluated Let's do what we could have done a while ago, reorder the statements

// Function to return a letter grade char letterGrade(int grade){ char letterGrade; if (grade > 89) letterGrade = 'A'; else if (grade > 74) letterGrade = 'B'; else if (grade > 59) letterGrade = 'C'; else if (grade > 50) letterGrade = 'D'; else // (grade < 50) letterGrade = 'F'; return letterGrade; } This works correctly, the same plan could have been used to fix the first version The function checks for an A, then for a B, then for a C, then for a D, if none of those apply the grade must be an F (else)

lg = 'F' gr > 89 true lg = 'A' false char letterGrade(int grade){ char letterGrade; if (grade > 89) letterGrade = 'A'; else if (grade > 74) letterGrade = 'B'; else if (grade > 59) letterGrade = 'C'; else if (grade > 50) letterGrade = 'D'; else // (grade < 50) letterGrade = 'F'; return letterGrade; } char letterGrade(int grade){ char letterGrade; if (grade > 89) letterGrade = 'A'; else if (grade > 74) letterGrade = 'B'; else if (grade > 59) letterGrade = 'C'; else if (grade > 50) letterGrade = 'D'; else // (grade < 50) letterGrade = 'F'; return letterGrade; } gr > 74 true lg = 'B' false gr > 59 true lg = 'C' false gr > 50 true lg = 'D' false return lg return lg

 An if statement does not have to have an associated else statement  An else statement does need an associated if statement  Else statements are always matched to the closest if (or else if) statement  Regardless of indentation

 C has a shorthand for an if else statement  The conditional operator  The operator is a two part operator with three operands  A ternary operator  The operator consists of the following  A Boolean expression followed by a ?  A value  A : followed by a value

store the absolute value of x in y if (y < 0) x = -y; else x = y; if (y < 0) x = -y; else x = y; the equivalent conditional expression x = (y < 0) ? -y : y; condition value if false value if true

 Switch statements can be used to choose between different cases  As long as the cases can be evaluated to an integer or a character  As another, grade-related, example let's write a function to print a message  That varies based on the grade

// Function to print a message about a letter grade void gradeMessage(char letterGrade){ switch(letterGrade) { case 'A': printf("Wow, an A, congratulations!\n"); case 'B': printf("Well done, you got a B\n"); case 'C': printf("You passed, with a C\n"); case 'D': printf("It was close but you passed, a D\n"); case 'F': printf("Too bad, so sad, you failed\n"); default: printf(“Error!\n"); } The statement after the first matching case is executed, then all of the following statements Well done, you got a B You passed, with a C It was close but you passed, a D Too bad, so sad, you failed Error! Well done, you got a B You passed, with a C It was close but you passed, a D Too bad, so sad, you failed Error! output from calling gradeMessage(‘B’) :

// Function to print a message about a letter grade void gradeMessage(char letterGrade){ switch(letterGrade) { case 'A': printf("Wow, an A, congratulations!\n"); break; case 'B': printf("Well done, you got a B\n"); break; case 'C': printf("You passed, with a C\n"); break; case 'D': printf("It was close but you passed, a D\n"); break; case 'F': printf("Too bad, so sad, you failed\n"); break; default: printf(“Error!\n"); } The break statement immediately moves to the end of the switch statement body (the closing } ) Well done, you got a B gradeMessage(‘B’): Error! gradeMessage(‘b’):

// Function to print a message about a letter grade void gradeMessage(char letterGrade){ switch(letterGrade) { case 'A': case 'a': printf("Wow, an A, congratulations!\n"); break; case 'B': case 'b': printf("Well done, you got a B\n"); break; case 'C': case 'c': printf("You passed, with a C\n"); break; case 'D': case 'd': printf("It was close but you passed, a D\n"); break; case 'F': case 'f': printf("Too bad, so sad, you failed\n"); break; default: printf(“Error!\n"); } Well done, you got a B gradeMessage(‘b’):

 The switch test expression and the case labels must be integer values  Which includes the char type  Therefore switch statements cannot be used in the following situations  To evaluate floats, or other non integer types  To evaluate ranges of values ▪ At least without creating many cases

 C has a goto statement  That directs execution to a labelled statement in the same function  Avoid the use of goto statements  They are unnecessary and their effect can be achieved by the use of other constructs  Goto statements make programs very difficult to read, and therefore hard to modify