Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 2 Flow of Control. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-2 Learning Objectives Boolean Expressions Building, Evaluating.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Introduction to Computers and Programming Lecture 6 Professor: Evan Korth New York University.
1 9/24/07CS150 Introduction to Computer Science 1 Relational Operators and the If Statement.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
true (any other value but zero) false (zero) expression Statement 2
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Logical and Relational Expressions Nested if statements.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
Computer Science Selection Structures.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
VBScript Language. What is VBScript Based on the Visual Basic family of languages Supports object oriented features Interpreted Loosely Typed Implicitly.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 3 (2) & 4 September 8 & 10, 2009.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Lesson - 5. Introduction While programming, we usually need to decide the path of the program flow according to the parameters and conditions. Actually.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Introduction to branching.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 3 Decisions Three control structures Algorithms Pseudocode Flowcharts If…then …else Nested if statements Code blocks { } multi statement blocks.
Decision Statements, Short- Circuit Evaluation, Errors.
CPS120: Introduction to Computer Science Decision Making in Programs.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Rational Expressions relational operators logical operators order of precedence.
 Type Called bool  Bool has only two possible values: True and False.
University of Central Florida COP 3330 Object Oriented Programming
Rational Expressions. relational operators. logical operators
University of Central Florida COP 3330 Object Oriented Programming
Operator Precedence Operators Precedence Parentheses () unary
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Boolean Expressions and If
Topics The if Statement The if-else Statement Comparing Strings
Boolean Expressions & the ‘if’ Statement
Programming Fundamentals
Topics The if Statement The if-else Statement Comparing Strings
Chapter 8 JavaScript: Control Statements, Part 2
Summary Two basic concepts: variables and assignments Basic types:
Structural Program Development: If, If-Else
Presentation transcript:

CMPT 128: Introduction to Computing Science for Engineering Students Logical and Relational Expressions and Logical and Relational Operators

Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches In sequence Branching Looping © Janice Regan, CMPT 128, 2007-2013

Control Structures Branch: Altering the flow of program execution by making a selection or choice Loop: Altering the flow of program execution by repetition of a particular block of statement(s) © Janice Regan, CMPT 128, 2007-2013

Branching One way selection Two way selection Multiple way selection © Janice Regan, CMPT 128, 2007-2013

One-way selection Simplest form of a branch. Evaluate a condition that can be True or False If the condition is true a series of actions are executed If the condition is false that series of actions are not executed C and C++ implementation: if statement © Janice Regan, CMPT 128, 2007-2013

Two-way selection C and C++ implementation: Evaluate a condition that can be True or False One “Set of things to do” if the condition is true, A different “Set of things to do” if the condition is false C and C++ implementation: if-else statement © Janice Regan, CMPT 128, 2007-2013

Multiple-way selection If condition1 is true the 1st series of actions is completed If condition1 is false and condition2 is true the 2nd series of actions is completed If condition1 and condition2 are false and condition3 is true the 3rd series of actions is completed … If all conditions are false the final series of actions is completed Implemented in C++ as an if-elseif-else statement © Janice Regan, CMPT 128, 2007-2013

Selection: decision statements Each decision statement contains a condition The condition is an expression with a logical value (true or false) The condition is a Boolean expression A relational expression (a type of logical expression) Another type of logical expression A Boolean variable or constant © Janice Regan, CMPT 128, 2007-2013

Relational Expressions A type of logical expression Combines two numbers, strings, characters to give a value of true or false A simple relational expression is Two numerical values combined using a binary relational operator A more complex relational expression is A combination of simple relational expressions © Janice Regan, CMPT 128, 2007-2013

Binary Relational Operators C, C++ < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to Evaluated left to right Binary Equality Operators in C, C++ We don’t get into details here, wrt integer division and exponentiation If they ask, Integer division returns an integer result (truncated toward zero) If left side of ** is integer, right side must be nonnegative (Natural). In any case RHS of exponentiation is an integer. © Janice Regan, CMPT 128, 2007-2013

Other logical expressions Other types of logical expression include Two logical variables / constants combined with a binary logical operator One logical variable or constant One logical variable or constant operated on by a unary logical operator Two relational expressions combined with a binary logical operator … Any more complex logical expression © Janice Regan, CMPT 128, 2007-2013

Binary Logical Operators C, C++ && Logical AND || Logical OR ! Not Evaluated left to right Arguments of logical operators have values of true or false Unary Logical Operators C, C++ © Janice Regan, CMPT 128, 2007-2013

C and C++ Boolean values In C++ Boolean variables or constants Have type bool and value true or false Have integer values consistent with C In C Boolean values (true and false) are represented as integers All non-zero integer values  true Zero value  false Newest version of standard C99 has type bool © Janice Regan, CMPT 128, 2007-2013

Truth Table && The && (And) operator T T T T F F F T F F F F EXPRESSION1 EXPRESSION2 EXPRESSION1 && EXPRESSION2 T T T T F F F T F F F F © Janice Regan, CMPT 128, 2007-2013

The || (Inclusive Or) operator Truth Tables || The || (Inclusive Or) operator EXPRESSION1 EXPRESSION2 EXPRESSION1 || EXPRESSION2 T T T T F T F T T F F F © Janice Regan, CMPT 128, 2007-2013

Truth Tables ! The ! (Not) operator T F F T EXPRESSION1 ! EXPRESSION1 © Janice Regan, CMPT 128, 2007-2013

Precedence of operators C, C++ ( ) [] . innermost first ++ -- (pre) + - ! ~(unary) (right to left) * / % + - < <= > >= == != && || = += -= *= /= %= (right to left) ?: © Janice Regan, CMPT 128, 2007-2013

Expressions with relational operators Value of a relational expression (expression including a relational or binary equality operator) is true or false. Arguments of a relational operator are numerical (or character) A < C Let A=9, B=5, C=2 A != -C © Janice Regan, CMPT 128, 2007-2013

Expressions: relational operators A < C Let A=9, B=5, C=2 9 2 A C A C < < F Value of expression is Boolean: In C++ Boolean (T or F) is represented by a bool type variable. © Janice Regan, CMPT 128, 2007-2013

Expressions: relational operators A * B <= C X <= C Let A=9, B=5, C=2 9 5 A B 35 2 X C * A B C * <= <= F Value of expression is Boolean: © Janice Regan, CMPT 128, 2007-2013

Expressions: logical operators Value of a relational expression or logical expression (expression including a logical operator) is true or false. Operands of the logical operator are true or false Therefore relational and logical expressions can be operands of logical expressions Let A=9, B=5, C=2 Then (C < B) && A ^ C !(A < B) && B<A © Janice Regan, CMPT 128, 2007-2013

The ^ (Bitwise Exclusive Or) operator Truth Tables ^ The ^ (Bitwise Exclusive Or) operator EXPRESSION1 EXPRESSION2 EXPRESSION1 ^ EXPRESSION2 T T F T F T F T T F F F © Janice Regan, CMPT 128, 2007-2013

Other bitwise operators Symbol Operator & bitwise AND binary | bitwise inclusive OR ^ bitwise exclusive OR << left shift unary >> right shift ~ bitwise NOT (one's complement) Bitwise operators compare the first bit of each variable to get the first bit of the answer, then the second bit of each variable to get the second bit of the answer, … © Janice Regan, CMPT 128, 2007-2013

Why is bitwise different Historically C used non-zero for true and zero for false, and had no Boolean type (C99 and newer has Boolean) Anything that could be represented as an integer could be compared If we bitwise AND two true variables X=1010 and Y=0101 it is possible to get the answer false (X&Y = 0000 ) If we AND two true variables we will always get the answer true (X &&Y = TRUE) If we allowed only Boolean variables as arguments for logical operators and have 0 for false and 1 for true, bitwise is not different. © Janice Regan, CMPT 128, 2007-2013

Expressions: logical operators Let A=9, B=5, C=2 (C < B) && (A ^ C) X && (A ^ C) X && Y 2 5 C B T X < 1001 ^ 0010 = 1011 9 2 A C A C T B Y ^ < && ^ T && Value of expression © Janice Regan, CMPT 128, 2007-2013

Expressions: logical operators Let A=9, B=5, C=2 !(A < B) && A > C !X && A > C Y && A > C Y && Z 9 5 A B X F < T Y ! 9 2 A C Z T > A B C < ! && > && T Value of expression © Janice Regan, CMPT 128, 2007-2013

Precedence Examples Arithmetic before logical Short-circuit evaluation (x >= 0) && (y > 1) Be careful with increment operators! (x > 1) && x<y++ © Janice Regan, CMPT 128, 2007-2013

Expressions: logical operators Let A=9, B=5, C=2 !(A < B) || A > C !X || A > C Y || A > C Short Circuit 9 5 A B F X < T Y ! A B C < || ! T Value of expression © Janice Regan, CMPT 128, 2007-2013

Expressions: logical operators Let A=9, B=5, C=2 A < B && B < C++ X && B < C++ Short Circuit (increment not evaluated!) 9 5 A B F X < && A B C F < Value of expression && © Janice Regan, CMPT 128, 2007-2013

Selection Structure Use a decision statement when an action is to be taken only if a particular condition holds The condition which must hold may be logical or relational expression or a Boolean variable. The value of the condition must be true or false Each possible path through a condition statement will contain a sequence of steps to be executed The condition and the sequences of steps that are executed for each outcome of the condition statement form a selection structure. A selection structure is a type of control structure © Janice Regan, CMPT 128, 2007-2013

Flowcharts Flowcharts use some basic symbols To start or end a function To contain calculations To make decisions To connect different parts of an algorithm © Janice Regan, CMPT 128, 2007-2013

Flowchart: one way selection Write the condition that needs to be satisfied in the decision box (diamond). Based upon the value of the condition (boolean T or F) choose what to do next The sequence of statements to be executed if the condition is true is placed in the box C and C++ implementation if statement T Statement 1; Statement n; condition ⋮ F © Janice Regan, CMPT 128, 2007-2013

One-way selection Example if statement in C and C++: setFlagOrderBoxes = 0; if (numberOfBoxes < minimumBoxInventory) setFlagOrderBoxes = 1; setFlagOrderBags = 0; // always executed setFlagOrderBags is always set to 0, even if the condition in the if statement is false © Janice Regan, CMPT 128, 2007-2013

C++ Compound/Block Statement Only one statement following the if statement is part of the if control structure What if we need more than one statement done if the condition is true? Must use a block of statements (also called a compound statement) C++ uses { }, to contain all the statements in a block of statements © Janice Regan, CMPT 128, 2007-2013

One way selection: sample Do a series of actions only if a given condition holds If the condition does not hold skip the actions if (myScore > yourScore) { cout << “My score was higher than yours “; difference = myScore – yourScore; cout << “I got “ << difference << “ more points than you did” ; } © Janice Regan, CMPT 128, 2007-2013

Course coding standard When writing an if statement you should always use a block Always use the { } even if the block contained within the { } includes just one statement © Janice Regan, CMPT 128, 2007-2013

Justification WHY use the { } if there is only one statement in the block? As your code evolves it is common to add statements (functionality) within a decision statement. When you add statements and forget to add the {} to indicate the extent of the block unexpected things happen. The resulting problems can be difficult to find © Janice Regan, CMPT 128, 2007-2013

Course coding standard To make your program easier to read, understand, debug, and maintain use the following approach Place the brackets { } that delimit each block (compound statement) each on their own line Indent each of the statements inside the block a given number (you choose and use consistently) of spaces farther from the left of the page than the brackets. © Janice Regan, CMPT 128, 2007-2013

Two-way selection Another type of simple branch structure Consider two different series of actions If a condition is true the first series of actions is completed If the same condition is false the second series of actions is completed © Janice Regan, CMPT 128, 2007-2013

Flowchart: two way selection Based upon the value of the condition (boolean T or F) choose what to do next The sequence of statements to be executed if the condition is true is placed in the box at the right The sequence of statements to be executed if the condition is false is placed in the box below the condition condition Statement 1; Statement n; T F ⋮ ⋮ Implemented in C and C++ as an if-else statement © Janice Regan, CMPT 128, 2007-2013

Example of two-way selection Example if-else statement in C and C++: if (examScore > 50) myCourseGrade = “PASS”; else myCourseGrade = “FAIL”; NOTE: Only one statement follows the if, and one statement follows the else © Janice Regan, CMPT 128, 2007-2013

Common Error in C++ Operator = is the "assignment" operator Operator == is the logical operator to test equality of two variables These two operators are VERY different Avoid the following common error: if (x = 12) Do_thing1; else Do_thing2; © Janice Regan, CMPT 128, 2007-2013

What actually happens Common Error in C and C++ Boolean variables have values true or false in C++. In earlier versions of C there was no Boolean type, true and false were represented by integers 0 is false Non zero is true C++ is backward compatible with C, so recognizes the integer representation used in C So if(x=12) evaluates to true (12) and thing1 is done (regardless of the original value of x) The value 12 is assigned to x (the value of x becomes 12) if(12) is the same as if(true) and evaluates to true © Janice Regan, CMPT 128, 2007-2013

Compound/Block Statement Must use a compound statement { } to include more than one statement following the if or more than one statement following the else Course Coding Standard Each block (after the if and after the else) should have block statement using { } even if the block contains just one statement © Janice Regan, CMPT 128, 2007-2013

Two way selection in C++ Complete one of two possible series of actions First series of actions is complete if condition is true Second series of actions is completed if condition is false if (condition) { //Series of actions to be taken when the condition is true action 1; ⋮ action n; } else { // Series of actions to be taken when the condition is false © Janice Regan, CMPT 128, 2007-2013

Flowchart for multiple selection Statement 1; Statement n; T ⋮ condition F Statement 1; Statement n; condition2 T ⋮ F Statement 1; Statement n; ⋮ © Janice Regan, CMPT 128, 2007-2013

Example of Multiple selection if (examScore > 80) myCourseGrade = “A”; else if (examScore > 60) myCourseGrade = “C”; else myCourseGrade = “FAIL”; © Janice Regan, CMPT 128, 2007-2013

Multiple-way selection If condition1 is true the 1st series of actions is completed If condition1 is false and condition2 is true the 2nd series of actions is completed If condition1 and condition2 are false and condition3 is true the 3rd series of actions is completed … If all conditions are false the final series of actions is completed Implemented in C++ as an if-elseif-else statement © Janice Regan, CMPT 128, 2007-2013

Multiple Selections (else if) if (condition1) { // Series of actions to be taken when condition 1 is true action 1; action n; } else if (condition 2) { // actions to be taken when condition 1 is false and condition2 is true else // Series of actions to be taken when condition 1and condition 2 are false © Janice Regan, CMPT 128, 2007-2013

Course coding standard for ifs Each if, elseif, and else should put all statement to be executed for the case in a block statement using { }. A block statement should be used even if the block contains just one statement. Place the brackets { } that delimit each block (compound statement) each on their own line Indent each of the statements inside the block a specified number of spaces farther from the left of the page than the brackets. © Janice Regan, CMPT 128, 2007-2013