Sie sind auf Seite 1von 39

Chapter 4

Control Structures I (Selection)

Outline
1.

Control Structures

2.

Relational Operator

3.

Logical (Boolean) Operators and Logical


Expressions

4.

Selection: if and if else

5.

switch Structures

6.

Terminating a Program with the assert Function

7.

Exercises

1. Control Structures

statement1
false

expression

true

statement2
statement

.
.
.

statement2

statement1

statementN

true

false

b. Selection
a. Sequence

expression

expression

c. Repetition

1. Control Structures: Conditional Statements

if (score is greater than or equal to 90)


grade is A

if (hours worked are less than or equal to 40)


wages = rate * hours

otherwise
wages = (rate * 40) + 1.5 * (rate * (hours - 40))

if (temperature is greater than 70 degrees and its not


raining)
Go golfing!

2. Relational Operator

In C++, a condition is represented by a logical


(Boolean) expression.

An expression that has a value of either true or false is


called a logical (Boolean) expression.

A relational operator allows you to make comparisons


in a program.

2. Relational Operator

Operator

Description

==

Equal to

!=

Not equal to

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

2. Relational Operator: Simple Data Types

Expression

Value

8 < 15

true

6 != 6

false

2.5 > 5.8

false

5.9 <= 7.5

true

2. Relational Operator: Comparing characters

Expression

Value

Explanation

< a

true

The ASCII value of is 32, and


the ASCII value of a is 97.

R > T

false

The ASCII value of R is 82, and


the ASCII value of T is 84.

+ < *

false

The ASCII value of + is 43, and


the ASCII value of * is 42.

6 <= >

true

The ASCII value of is 54, and


the ASCII value of > is 62.

2. Relational Operator: string Type

The relational operators can applied to variables of type string.

Variables of type string are compared character-by-character.

Expression

Value

Hello < Hi

true

Hello > Hen

false

Air < An

true

Hello == hello

false

Air <= Bill

true

3. Logical (Boolean) Operators and Logical Expressions

Operator

Description

not

&&

and

||

or

3. Logical (Boolean) Operators and Logical Expressions: !

Expression

!(Expression)

true (nonzero)

false (0)

false (0)

true (1)

Expression

Value

!(A > B)

true

!(6 <= 7)

false

3. Logical (Boolean) Operators and Logical Expressions: &&

Expression1

Expression2

Expression1 && Expression2

true (nonzero)

true (nonzero)

true (1)

true (nonzero)

false (0)

false (0)

false (0)

true (nonzero)

false (0)

false (0)

false (0)

false (0)

Expression

Value

(14 >= 5) && (A < B)

true

(24 >= 35) && (A < B)

false

3. Logical (Boolean) Operators and Logical Expressions: ||


Expression1

Expression2

Expression1 || Expression2

true (nonzero)

true (nonzero)

true (1)

true (nonzero)

false (0)

true (1)

false (0)

true (nonzero)

true (1)

false (0)

false (0)

false (0)

Expression

Value

(14 >= 5) || (A > B)

true

(24 >= 35) || (A > B)

false

(A <= a) || (7 != 7)

true

3. Logical (Boolean) Operators and Logical Expressions


Operators

Precedence

!, +, - (unary operators)

First

*, /, %

Second

+, -

Third

<, <=, >=, >

Fourth

==, !=

Fifth

&&

Sixth

||

Seventh

= (assignment operator)

last

3. Logical (Boolean) Operators and Logical Expressions


Operators

Precedence

!, +, - (unary operators)

First

*, /, %

Second

+, -

Third

<, <=, >=, >

Fourth

==, !=

Fifth

&&

Sixth

||

Seventh

= (assignment operator)

last

Example
(17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3 + 3 == 6)
= (17 < 12 + 5) || (16 == 16) && !(6 == 6)
= (17 < 17) || true && !(true)
= false || true && false
= false || false (because true && false is false)
= false

3. Logical (Boolean) Operators and Logical Expressions

int legalAge;
int age;
bool b;
legalAge = 21;
legalAge = (age >= 21); // legalAge = 1 if age >= 21, otherwise legalAge = 0
b = true;
b = (age >= 21); // b = true if age >= 21, otherwise b = false

4. Selection: if and if else: one-Way Selection


if (expression)
{
statements
}

if (expression)
statement

expression

false

true

statement

4. Selection: if and if else: one-Way Selection


Examples

Comments

double score;
cin >> score;
if (score >= 60)
grade = p;

Correct: grade will be assigned


the character p if score >= 60

double score;
cin >> score;
if score >= 60
grade = p;

Syntax error: the logical


expression is not enclosed by
two parenthesis.

double score;
cin >> score;
if (score >= 60);
grade = p;

Logical error: the semicolon at


the end of if will terminate the if.
grade will be assigned p
regardless the value of score.

4. Selection: if and if else: one-Way Selection

Examples

score

Output

if(score >= 60)

50

Failing

cout << Passing << endl;


cout << Failing << endl;

70

Passing
Failing

4. Selection: if and if else: one-Way Selection


Exercise: write a C++ code to find the absolute value
of an integer.
#include<iostream>
using namespace std;
int main()
{
int n, a;
cout << "Enter an integer number: ";
cin >> n;
cout << "The absolute value of " << n << " is ";
a = n;
if(n < 0)
a = -n;
cout << a << endl;
return 0;
}

4. Selection: if and if else: Two-Way Selection

false

expression

statement2

true

statement1

if (expression)
statement1
else
statement2

4. Selection: if and if else: Two-Way Selection

if(hours > 40.0);

// Syntax error

wages = 40.0 * rate + 1.5 * rate * (hours - 40.0);


else
wages = hours * rate;

The semicolon at the end of the if ends the if so


else will be separated from the if . This code
generates a syntax error.

4. Selection: if and if else: Two-Way Selection


Compound (Block of) Statements
if(age >= 18)
{
cout << "Eligible to vote." << endl;
cout << No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << Still a minor." << endl;
}

4. Selection: if and if else: Multiple Selections: Nested if

if(score >= 90)


cout << "The grade is A." << endl;
else if (score >= 80)
cout << "The grade is B." << endl;

Pairing an else with an if:

else if (score >= 70)

In a nested if statement, C+

cout << "The grade is C." << endl;

+ associates an else with

else if (score >= 60)

the most recent incomplete

cout << "The grade is D." << endl;

if

else
cout << "The grade is F." << endl;

4. Selection: if and if else: Multiple Selections: Nested if


if(GPA >= 2.0)
if(GPA >= 3.9)
cout << Deans Honor List." << endl;
else
cout << Current GPA below graduation requirement.
<< \nSee your academic advisor. << endl;

GPA
3.95
3.6
1.8

Output
Deans Honor List.
Current GPA below graduation requirement.
See your academic advisor.

4. Selection: if and if else: Multiple Selections: Nested if


if(month == 1)
cout << "January" << endl;
else if(month == 2)
cout << "February" << endl;
else if(month == 3)
cout << "March" << endl;
else if(month == 4)
cout << "April" << endl;
else if(month == 5)
cout << "May" << endl;
else if(month == 6)
cout << "June" << endl;

if(month == 1)
cout << "January" << endl;
if(month == 2)
cout << "February" << endl;
if(month == 3)
cout << "March" << endl;
if(month == 4)
cout << "April" << endl;
if(month == 5)
cout << "May" << endl;
if(month == 6)
cout << "June" << endl;

If month is 1, both programs will display January. But, only the first if of the
first program will be evaluated. The others will be ignored. However, in the
second program all the if statements will be evaluated.

5. switch Structures: Syntax


switch (expression)
{
case value1:
statements1
break;
case value2:
statements2
break;
.
.
.
case valuen:
statementsn
break;
default:
statements
}

5. switch Structures: Example


Write a switch statement to display the coefficient according to
the grade.

Grade

Coefficient

4.0

3.0

2.0

1.0

0.0

5. switch Structures: Example


Write a switch statement to display the coefficient according to
the grade.

Grade

Coefficient

4.0

3.0

2.0

1.0

0.0

5. switch Structures: Example


char grade;
cin.get(grade);
switch(grade)
{
case 'A':
cout << "The GPA coefficient is 4.0";
break;
case 'B':
cout << "The GPA coefficient is 3.0";
break;
case 'C':
cout << "The GPA coefficient is 2.0";
break;
case 'D':
cout << "The GPA coefficient is 1.0";
break;
case 'F':
cout << "The GPA coefficient is 0.0";
break;
default:
cout << "The grade is invalid";
}

5. switch Structures: Example


Suppose that score is an int variable representing the total mark
obtained by a student in all his exams. Write a switch statement to
assign the student his grade according to his score.
Score

Grade

Less than 60

60 score < 70

70 score < 80

80 score < 90

score 90

5. switch Structures: Example

int score;
cin >> score;
switch(score / 10)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break;
case 6:
grade = 'D';
break;

case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
grade = 'A';
break;
default:
cout << "The score is invalid" << endl;
}

5. switch Structures: Example


int age;
cin >> age;
switch(age >= 18)
{
case 1: // or case true
cout << "Old enough to be drafted." << endl;
cout << "Old enough to vote." << endl;
break;
case 0:
// or case false
cout << "Not old enough to be drafted." << endl;
cout << "Not old enough to vote." << endl;
}

6. Terminating a Program with the assert Function

Certain types of errors that are very difficult to catch may occur in
a program (for example division by zero).

C++ includes a predefined function, assert, to stop program run if


an error occurs (#include<cassert>).

Syntax: assert(expression); // expression is a logical expression

If expression evaluates to true, the next statement executes

If expression evaluates to false, the program terminates and


indicates where in the program the error occurred.

#define NDEBUG placed before #include<cassert> disables assert.

6. Terminating a Program with the assert Function

assert(denomenator); // if the value of denomenator is 0, the program stops running


quotient = numerator / denomenator;
assert(hours > 0 && (0 < rate && rate <= 15.50));
if (hours > 0 && (0 < rate && rate <= 15.50))
wages = rate * hours;

7. Exercises

Suppose the input is 5.


What is the value of
alpha
following
executes?

after

the

C++

code

int alpha;
cin >> alpha;
switch(alpha)
{
case 1:
case 2:
alpha = alpha + 2;
break;
case 4:
alpha++;
case 5:
alpha = 2 * alpha;
case 6:
alpha = alpha + 5;
break;
default:
alpha--;
}

7. Exercises

Suppose the input is 3.


What is the value of
beta after the following
C++ code executes?

int beta;
cin >> beta;
switch(beta)
{
case 3:
beta = beta + 3;
break;
case 1:
beta++;
break;
case 5:
beta = beta + 5;
case 4:
beta = beta + 4;
}

7. Exercises

Write a program that prompts the user to input


a number. The program should then output the
number and a message saying whether the
number is positive, negative, or zero.

7. Exercises

Write a program to solve


the quadratic equation.

Das könnte Ihnen auch gefallen