470 likes | 577 Vues
Learn about logical and relational expressions, operators, and control structures. Discover branching, looping, and multiple-way selections in C and C++.
E N D
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
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)
Branching • One way selection • Two way selection • Multiple way selection
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
Two-way selection • 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
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
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
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
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++
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
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++
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
Truth Table && The && (And) operator EXPRESSION1 EXPRESSION2 EXPRESSION1 && EXPRESSION2 T T T T F F F T F F F F
Truth Tables || The || (Inclusive Or) operator EXPRESSION1 EXPRESSION2 EXPRESSION1 || EXPRESSION2 T T T T F T F T T F F F
Truth Tables ! The ! (Not) operator EXPRESSION1 ! EXPRESSION1 T F F T
Precedence of operators C, C++ • ( ) [] . innermost first • ++ -- (pre) + - ! ~(unary) (right to left) • * / % • + - • < <= > >= • == != • && • || • = += -= *= /= %= (right to left) • ?:
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
Expressions: relational operators • A < C • Let A=9, B=5, C=2 9 2 C A < C A F < Value of expression is Boolean: In C++ Boolean (T or F) is represented by a bool type variable.
Expressions: relational operators • A * B <= C X <= C • Let A=9, B=5, C=2 9 5 B A 2 35 C X * C B A * <= <= F Value of expression is Boolean:
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
Expressions: logical operators 2 5 • Let A=9, B=5, C=2 • (C < B) && (A ^ C) X && (A ^ C) X && Y B C T X 1001 ^ 0010 = 1011 < 2 9 A C T A C B Y ^ < && ^ T && Value of expression
Expressions: logical operators 9 5 • Let A=9, B=5, C=2 • !(A < B) && A > C !X && A > C Y && A > C Y && Z B A F X < T Y ! 9 2 C A T Z > A B C < ! && > && T Value of expression
Precedence Examples • Arithmetic before logical • Short-circuit evaluation • (x >= 0) && (y > 1) • Be careful with increment operators! • (x > 1) && x<y++
Expressions: logical operators 9 5 • Let A=9, B=5, C=2 • !(A < B) || A > C !X || A > C Y || A > C Short Circuit B A F X < T Y ! A B C < || ! T Value of expression
Expressions: logical operators 9 5 • Let A=9, B=5, C=2 • A < B && B < C++ X && B < C++ Short Circuit (increment not evaluated!) B A F X < && A B C F < Value of expression &&
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
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
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
One-way selection • Example if statement in C and C++: setFlagOrderBoxes = 0; if (numberOfBoxes < minimumBoxInventory) setFlagOrderBoxes = 1; setFlagOrderBags = 0; // always executed • setFlagOrderBagsis always set to 0, even if the condition in the if statement is false
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
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” ;}
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
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
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.
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
T Statement 1; Statement n; condition F Statement 1; Statement n; 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 ⋮ ⋮ Implemented in C and C++ as an if-else statement
Example of two-way selection • Example if-else statement in C and C++: if (examScore > 50)myCourseGrade = “PASS”; elsemyCourseGrade = “FAIL”; • NOTE: Only one statement follows the if, and one statement follows the else
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;
What actually happensCommon 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
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
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 action 1; ⋮ action n; }
Flowchart for multiple selection Statement 1; Statement n; ⋮ T condition F Statement 1; Statement n; T condition2 ⋮ F Statement 1; Statement n; ⋮
Example of Multiple selection • Example: if (examScore > 80) myCourseGrade = “A”; else if (examScore > 60) myCourseGrade = “C”; else myCourseGrade = “FAIL”;
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
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 action 1; action n; } else { // Series of actions to be taken when condition 1and condition 2 are false action 1; action n; }
Course coding standard for ifs • Each if, elseif, and else should put all statement to be executed for the case in ablock 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.