Vous êtes sur la page 1sur 18

ENGR 1200U Introduction to Programming Lecture 9 Control Structures: Selection (Chapter 3)

Dr. Eyhab Al-Masri

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

An algorithm is a sequence of steps for solving a problem. Engineering problem solutions to real world problems require complex algorithms. Development of a good algorithm increases the quality and maintainability of a solution, and reduces the overall time required to implement a correct solution.

ENGR 1200U Winter 2013 - UOIT

Top-down design begins with a "big picture" description of a problem solution in sequential steps. The sequential steps are refined until the steps are detailed enough to translate to language statements. The refined steps, or algorithm, can be described using pseudo code or flowcharts.

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

Copyright 2012 Pearson Education, Inc.

A structured program is written using simple control structures, including:


Sequence steps are performed one after another. Selection one set of statements is executed if a given condition is true, a different set of statements, or no statements at all, is executed if the condition is false. Repetition A set of statements is executed repeatedly as long as a given condition is true.

ENGR 1200U Winter 2013 - UOIT

Sequence Selection Repetition


?
true false true

? => conditional expression


false

ENGR 1200U Winter 2013 - UOIT

A conditional expression is a Boolean expression that evaluates to true or false. Selection structures and repetition structures rely on conditional expressions. Relational operators and logical operators are used to form conditional expressions.

ENGR 1200U Winter 2013 - UOIT

Table 3..1: C++ for Everyone by Cay Horstman

ENGR 1200U Winter 2013 - UOIT

Assignment versus Equality


int c c = 5;

In C++, = is an assignment operator Example:

Use == inside tests Use = outside test

//assign value of 5 to c

The == operator denotes equality testing Example:


int c c = 5; if ( c == 5) If (name == Harry) //assign value of 5 to c // test whether c equals 5 //compare strings

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

Syntax 3.2: C++ for Everyone by Cay Horstman

ENGR 1200U Winter 2013 - UOIT

Table 3..2: C++ for Everyone by Cay Horstman

Value of x 12

Value of y 5

Expression x + 3 >= y * 3

Result true

10

x + 3 <= y * 10

false

17

x + 3 == y * 10

true

100

x + 3 > y * 10

true

ENGR 1200U Winter 2013 - UOIT

Simplified Syntax if (boolean_expression) statement;

if (boolean_expression) { statement1; statement_n; }

Examples //statement executed if x>0 if (x>0) ++k; //statement block executed if x>0 if (x>0) { x = sqrt(x); ++k; }
ENGR 1200U Winter 2013 - UOIT

If we wish to execute several statements (or a sequence structure) when the condition is true, we use a statement block

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

Syntax if (boolean_expression) statement; [else statement;]

if (boolean_expression) { } [else { }]

Example if (x>0) { //statement block executed if x>0 } else { } //statement block executed if x<=0

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

C++ allows a conditional operator to be used in place of a simple if/else statement Syntax: condition ? value1 : value2

if (age>65) { retired=age>65?true :false; retired=true; } else { retired=false; } cout<<"Retirementstatus:" <<(age>65?true :false);

ENGR 1200U Winter 2013 - UOIT

It is a common error to use the assignment operator (=) instead of the relational operator (==) Consider the following program
int x(4),y(5); if (x=y) { ThisislegalinC++,butwhatdoesit reallymean

cout<<x<<"isequalto" <<y<<endl; }

ENGR 1200U Winter 2013 - UOIT

We need to write code to determine student class status based on final grade (Pass or Fail).

How can we achieve this programmatically?

ENGR 1200U Winter 2013 - UOIT

10

We will model a person entering a grade by getting input from the user:
intgrade; cout<<"Grade:"; cin>>grade;

ENGR 1200U Winter 2013 - UOIT

If the user inputs any grade value greater than or equal to 50 Otherwise
We simply set the class status to 0
int class_status; if (grade>49) {class_status=1;} else {class_status=0;}

The program must set the class status to 1

ENGR 1200U Winter 2013 - UOIT

11

Braces are not required if the branch contains a single statement, but it is a good practice to include them.

A condition that is true or false. Often uses relational operators == != < <= > >=

Omit the else branch if there is nothing to do

if (grade>49) { class_status=1; } else { class_status=0; }


Lining up braces is a good practice

Dont put a semicolon here!

If the condition is true, the statement(s) in this branch are executed in sequence; if the condition is false, they are skipped. If the condition is false, the statement(s) in this branch are executed in sequence; if the condition is true, they are skipped.

ENGR 1200U Winter 2013 - UOIT

Condition

grade > 49?

class_status = 1

class_status = 0

ENGR 1200U Winter 2013 - UOIT

12

#include <iostream> using namespace std;

int main() {
int grade; Do you see cout<<"Grade:"; anything curious cin>>grade; in this code? int class_status; if (grade>49) { class_status=1; cout<<"Basedonyourgrade,yourstatusis:" <<class_status<<endl; } else { class_status=0; cout<<"Basedonyourgrade,yourstatusis:" <<class_status<<endl; } Do these statements return 0;

ENGR 1200U } 2013 - UOIT Winter

depend on the test?

#include <iostream> using namespace std;

int main() {
int grade; cout<<"Grade:"; cin>>grade; int class_status; if (grade>49) { class_status=1; } else { class_status=0; }

You should avoid this duplication.

cout<<"Basedonyourgrade,yourstatusis:" <<class_status<<endl;
ENGR 1200U } 2013 - UOIT Winter

return 0;

13

To avoid confusion and possible errors when using if/else statements, you should use {} to clearly define statement blocks. Do not use == with real values
Instead of x==3.14, use fabs(x-3.14)<0.0001

Do not confuse relational equality and assignment operators!

ENGR 1200U Winter 2013 - UOIT

Comparing strings uses lexicographical order (dictionary order) for determining which string is larger, smaller, or both are equal
stringstr1="Sarah"; stringstr2="Henry"; if (str1>str2) cout<<"HenrycomesbeforeSarahinthedictionary\n"; else if (str1<str2) cout<<"SarahcomesbeforeHenryinthedictionary\n"; else cout<<"Bothnamesareequal\n";

ENGR 1200U Winter 2013 - UOIT

14

String ordering rules:

All uppercase letters come before the lowercase letters


Example: Z comes before a

Space character comes before all printable characters Numbers come before letters Punctuation marks are ordered

ENGR 1200U Winter 2013 - UOIT

stringword1,word2; word1="Tremendous"; word2="Small"; Expression word1 == word2 Value false Result Both words are not equal in the first character T comes after S in lexicographical ordering Fifth characters do not match, and b comes before e They are equal

word1 > word2

true

word1 < Tremble

False

ENGR 1200U Winter 2013 - UOIT

Word2 == Small

True

15

bool Data Type

A built-in data type consisting of jus two values: true or false bool (a reserved C++ keyword) is short for Boolean Boolean data is used for testing conditions in a program Each variable of type bool can contain one of two values: true or false

ENGR 1200U Winter 2013 - UOIT

In C++, assertions take the form of logical expressions (also called Boolean expressions) Just as an arithmetic expression consists of numeric values and operations, a logical expression is made up of logical values and operations
Every logical expression has one of two values: true or false

ENGR 1200U Winter 2013 - UOIT

16

Logical Operator

! && ||

Operation

NOT AND OR

By combining logical operators with relational operators, we can make more complex assertions
Example:
grade >= 50.0 && grade <=60.0

ENGR 1200U Winter 2013 - UOIT

A false false true true

B false true false true

A&&B false false false true

A||B false true true true

!A true true false false

!B true false true false

Truth table for conditional expressions

ENGR 1200U Winter 2013 - UOIT

17

Consider the following logical expression


x == 1 && y > 2

Some programming languages use full evaluation of logical expressions


Computer first evaluates both subexpressions (both x == 1 and y > 2) before applying && operator to produce the final result

In contrast, C++ uses short-circuit (or conditional evaluation

ENGR 1200U Winter 2013 - UOIT

Evaluation proceeds from left to right, and the computer stops evaluating subexpressions as soon as possible (i.e. as it knows the Boolean value of the entire expression) Examples

E.g. if A is false, A && B is always false, regardless of the value of B. E.g. if A is true, A || B is always true, regardless of the value of B.

ENGR 1200U Winter 2013 - UOIT

18

Vous aimerez peut-être aussi