Top Banner
1 Control Statements: Part I Chapter 4
30

1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

Jan 04, 2016

Download

Documents

Kimberly Morton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

1

Control Statements: Part I

Chapter 4

Control Statements: Part I

Chapter 4

Page 2: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

2

Introduction

• Three building blocks for C++ control– Sequence structure– Selection structure– Repetition structure

• Operators– Assignment operators– Increment/decrement operators

Page 3: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

3

Algorithms

• Algorithm is a procedure of solving a problem in terms of– The actions to execute and– The order in which these actions execute

• Program control– Specify the order in which statements execute

Page 4: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

4

Pseudocode

• Pseudocode– An artificial and informal language that helps

programmer develop algorithms– Normally describes only executable statements (not

variable declarations)

Prompt the user to enter 1st integerInput the first integer Prompt the user to enter the 2nd integerInput the 2nd integer

Add first integer and second integer, store resultsDisplay result

Page 5: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

5

Control Structures

• Sequential execution– Execute one statement after the other in which they are written

• Transfer of control– Next one in sequence may not be next statement to execute– Indiscriminate use of transfer of control (goto statement) cause

tremendous difficulty for software developers

• Structured programming (Bohm and Jocopini)– Goto elimination– More likely to be bug free– Clear, easier to debug and modify– Reduced development time

• Control structures– Sequence structure– Selection structure– Repetition structure

Page 6: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

6

Sequence Structure in C++

Sequence-structure activity diagram

Initial state

Final state

Action state symbol

Notes

Page 7: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

7

Selection Statements in C++

• Single-selection statement (if)– Selects or ignores a single action

• Double-selection statement (if…else)– Selects between two different actions

• Multiple-selection statement (switch)– Selects among many different actions (groups

of actions)

Page 8: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

8

Repetition Statements in C++

• Performs statements repeatedly as long as a condition (loop-continuation condition) remains true

• Three types of repetition statements– while

• Perform the action(s) in its body zero or more times

– For• Perform the action(s) in its body zero or more times

– do…while• Perform the action(s) in its body at least once

Page 9: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

9

C++ keywords

auto break case char constcontinue default do double elseenum extern float for gotoif int long register returnshort signed sizeof static structswitch typedef union unsigned voidvolatile while

and and_eq asm bitand bitorbool catch class compl const_castdelete dynamic_cast explicit export falsefriend inline mutable namespace newnot not_eq operator or or_eqprivate protected public reinterpret_cast static_casttemplate this throw true trytypeid typename using virtual wchar_txor xor_eq

C++ only keywords

Keywords common to C and C++ languages

Page 10: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

10

Common Programming Errors Related to Keywords

• Using a keyword as an identifier is a syntax error

• Spelling a keyword with any uppercase letters is a syntax error. All of C++’s keywords contain only lowercase letters

Page 11: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

11

Connect Control Statements

• Model each control statement as an activity diagram– Initial state represents the entry point– Final state represents the exit point

• Control-statement stacking– Control statements are attached to one another by

connecting the exit point of one to the entry point of the next

• Control-statement nesting– One control statement is contained inside another

Page 12: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

12

if Single-selection Statement

Decision symbol

Associated guard conditionEvaluates to be true or false

Transition arrow

Single-entry /single-exit

Guard conditions can be boolean expressions or any expressions that evaluate to a number.Boolean expression: true or falseAny expression: zero (false), non-zero (true)

Page 13: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

13

if…else Double-selection Statement

Conditional operator (?:): only ternary operator in C++

cout << (grade>=60 ? “Passed” : “Failed”);

Page 14: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

14

Nested if…else Statements

if ( studentGrade >= 90 ) // 90 and above gets "A"

cout << "A";

else

if ( studentGrade >= 80 ) // 80-89 gets "B"

cout << "B";

else

if ( studentGrade >= 70 ) // 70-79 gets "C"

cout << "C";

else

if ( studentGrade >= 60 ) // 60-69 gets "D"

cout << "D";

else // less than 60 gets "F"

cout << "F";

Page 15: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

15

Cont’

if ( studentGrade >= 90 ) // 90 and above gets "A"

cout << "A";

else if ( studentGrade >= 80 ) // 80-89 gets "B"

cout << "B";

else if ( studentGrade >= 70 ) // 70-79 gets "C"

cout << "C";

else if ( studentGrade >= 60 ) // 60-69 gets "D"

cout << "D";

else // less than 60 gets "F"

cout << "F";

A nested if…else statement can perform much faster than a series of single-selection if statements because of the possible early exit

In a nested if…else statement, test the most likely condition first to maximize the chance of early exit

Programming Tips

Page 16: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

16

Dangling-else Problem

The C++ compiler always associates an else with the immediately preceding if unless told to do otherwise by the placements of braces. This behavior can lead to dangling-else problem.

if ( x > 5 )

if ( y > 5 )

cout << "x and y are > 5";

else

cout << "x is <= 5";

if ( x > 5 )

{

if ( y > 5 )

cout << "x and y are > 5";

}

else

cout << "x is <= 5";

Dangling-else

Correct

Page 17: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

17

Blocks

• if selection statement and if…else statement normally expect only one body statement

• Enclose several statements in the body of an if or in either part of an if…else with a pair of curly braces

• A set of statements contained in a pair of braces is called compound statement or a block

– A block can be placed anywhere in a program that a single statement can be placed– Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic

errors– Always putting the braces in an if…else statement helps prevent their accidental omission

• Null Statement (Empty statement)– Placing a semicolon (;) where a statement would normally be– Placing a semicolon after the condition in an if statement leads to a logic error in single-

selection if statements and a syntax error in double selection if…else statements (when the if part contains an actual body statement)

Page 18: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

18

while Repetition Statement

Joins the transitions from the initial state and the action state

Page 19: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

19

Infinite Loop

Cause:No action in the while body to cause the condition to become false.

Results:Repetition statement never terminatesProgram appears to “hang” or “freeze”

int i = 1;int factorial = 1;while(i>0){

factorial = factorial*i;i++;

}

Infinite Loop

Page 20: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

20

Formulating Algorithms: Counter-Controlled RepetitionDefinite Repetition

Problem statement:A class of ten students took a quiz. The grades for the quiz are available to you. Calculate and display the total of all student grades and the class average on the quiz.

Set total to zeroSet grade counter to one

While grade counter is less than or equal to tenPrompt the user to enter the next gradeInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the total of the grades for all students in the classPrint the class average

Pseudocode

Repetition terminates when counter exceeds 10

Update the counter

Page 21: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

21

Off-by-one-error

Cause:Use a loop’s counter-control variable in a

calculation after the loopResult:

The loop terminates when the counter’s value is one higher than its last legitimate value (i.e., 11 in the case of counting from 1 to 10)

Page 22: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

22

Formulating Algorithms: Sentinel-Controlled Repetition

Problem statement:Develop a class average algorithm that process grades for an arbitrary number of students each time it is run.

Initialize total to zeroInitialize counter to zero //avoid off-by-one-error

Prompt the user to enter the first gradeInput the first grade (possibly the sentinel)

While the user has not yet entered the sentinelAdd this grade into the running totalAdd one to the grade counterPrompt the user to enter the next gradeInput the next grade (possibly the sentinel)

If the counter is not equal to zeroSet the average to the total divided by the counterPrint the total of the grades for all students in the classPrint the class average

ElsePrint “No grades were entered”

Sentinel value is -1

Proper message with information on sentinel value

Page 23: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

23

Sentinel-Controlled Repetition vs Counter-Controlled Repetition

• Counter-controlled repetition– Each iteration of the while statement reads a

value from the user, for the specified number of iterations

• Sentinel-controlled repetition– The program reads the first value before

reaching the while– The body of while may never execute (e.g.,

no grades were entered)

Page 24: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

24

Explicit and Implicit Conversion between Fundamental Types

double average;average = static_cast<double> (total)/gradeCounter;

Explicit conversion is done by unary cast operator

gradeCounter is promoted to double (implicit conversion)

Page 25: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

25

Formatting for Floating-Point Numbers

• Nonparameterized stream manipulator– endl, fixed, showpoint, left, right(default)

– Do not require <iomanip> header file

• Parameterized stream manipulator– Require #include <iomanip>– cout << “Class average is “ << setprecision(2) << fixed << average << endl;

Round number to 2 decimal places

Page 26: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

26

Formulating Algorithms: Nested Control Statements

Problem statement:You have been given a list of these 10 students. Next to each name is written a 1 if the student passed or a 2 if the student failed. You have been asked to summarized the results in terms of number of passes and fails.

Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

While student counter is less than or equal to 10Prompt the user to enter the next exam resultInput the next exam resultIf the student passed

Add one to passesElse

Add one to failuresAdd one to student counter

Print the number of passesPrint the number of failures

If more than eight students passedPrint “Raise tuition”

If…else is nested in

while body

Page 27: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

27

Arithmetic Assignment Operators

Assignment operator

Sample expression

Explanation Assigns

Assume: int c=3, d=5, e=4, f=6, g=12;

+= c += 7 c = c + 7 10 to c

-= d -= 4 d = d - 4 1 to d

*= e *= 5 e = e * 5 20 to e

/= f /= 3 f = f / 3 2 to f

%= g %= 9 g = g % 9 3 to g

Page 28: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

28

Increment and Decrement Operators

Operator Called Sample expression

Explanation

++ Preincrement ++a Increment a by 1, then use the new value of a in the expression in which it resides

++ Postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1

-- Predecrement --b Decrement b by 1, then use the new value of b in the expression in which it resides

-- Postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1

Page 29: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

29

Example: Preimcrementing and Postincrementing

int main()

{

int c;

// demonstrate postincrement

c = 5; // assign 5 to c

cout << c << endl; // print 5

cout << c++ << endl; // print 5 then postincrement

cout << c << endl; // print 6

cout << endl; // skip a line

// demonstrate preincrement

c = 5; // assign 5 to c

cout << c << endl; // print 5

cout << ++c << endl; // preincrement then print 6

cout << c << endl; // print 6

return 0; // indicate successful termination

} // end main

Page 30: 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

30

Operator Precedence

Operators Associativity Type

() Left to right Parenthesis

++ -- static_cast<type>() Left to right Unary (postfix)

++ -- + - Right to left Unary (prefix)

* / % Left to right Multiplicative

+ - Left to right Additive

<< >> Left to right Insertion/extraction

< <= > >= Left to right Relational

== != Left to right Equality

?: Right to left Conditional

= += -= *= /= %= Right to left Assignment