+ All Categories
Home > Documents > Controlling Function Behavior Sequence, Selection and Repetition.

Controlling Function Behavior Sequence, Selection and Repetition.

Date post: 02-Jan-2016
Category:
Upload: asher-alexander
View: 220 times
Download: 0 times
Share this document with a friend
23
Controlling Function Controlling Function Behavior Behavior Sequence, Selection and Repetition Sequence, Selection and Repetition
Transcript

Controlling Function Controlling Function BehaviorBehavior

Sequence, Selection and RepetitionSequence, Selection and Repetition

ReviewReview

We’ve seen that we can write a simple We’ve seen that we can write a simple function that encodes a formula:function that encodes a formula:

double EllipseArea(double length, double width);{ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

The statements in such a function are The statements in such a function are executed in sequence (one after another), executed in sequence (one after another), which is called which is called sequential executionsequential execution..

DifficultyDifficultyThere are other operations that are There are other operations that are

difficult to implement, using just difficult to implement, using just sequential execution.sequential execution.

Example: Let’s write a program to read in Example: Let’s write a program to read in a sequence of test scores, and display a sequence of test scores, and display their average and a corresponding their average and a corresponding pass/fail grade.pass/fail grade.

BehaviorBehavior

Our program should prompt for, read, Our program should prompt for, read, and average a sequence of test scores. and average a sequence of test scores. It should then display the average. It It should then display the average. It should then compute the pass-fail should then compute the pass-fail letter grade (P or F) corresponding to letter grade (P or F) corresponding to that average. Finally, it should display that average. Finally, it should display that letter grade.that letter grade.

ObjectsObjects

Description Type Kind NameDescription Type Kind Name

average double varying averageP/F grade char varying grade

sequence of ??? ??? ??? test scores

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Nameprompt for, read no -- -- and average a sequence of doubles

display a double yes iostream <<compute grade no -- --display char yes iostream <<

AlgorithmAlgorithm

0. Display via cout the purpose of the program.0. Display via cout the purpose of the program.

1. Compute 1. Compute averageaverage by prompting for, reading and by prompting for, reading and averaging a sequence of test scores.averaging a sequence of test scores.

2. Display 2. Display averageaverage..

3. Compute P/F letter 3. Compute P/F letter gradegrade corresponding to average. corresponding to average.

4. Display 4. Display gradegrade..

DiscussionDiscussion

We have predefined operations for steps We have predefined operations for steps 0, 2 and 4 of our algorithm, but no 0, 2 and 4 of our algorithm, but no predefined operations for steps 1 or predefined operations for steps 1 or 3...3...

Solution: Build functions to perform Solution: Build functions to perform those operations.those operations.

Function 1 BehaviorFunction 1 Behavior

Our function should read, sum, and Our function should read, sum, and count the sequence of scores using the count the sequence of scores using the input-loop pattern. If the number of input-loop pattern. If the number of scores was positive, it should return scores was positive, it should return sum/numScores. Otherwise sum/numScores. Otherwise (numScores is not positive) it should (numScores is not positive) it should display an error message and display an error message and terminate the program.terminate the program.

Function 1 ObjectsFunction 1 Objects

Description Type Kind NameDescription Type Kind Name

sum of scores double varying sum

a score double varying score

number of int varying numScores scores

a prompt string constant --

error msg string constant --

Function 1 OperationsFunction 1 Operations

Description Predefined? Library? NameDescription Predefined? Library? Name

test for sentinel yes built-in <

display a string yes iostream <<read a double yes iostream >>

add score to sum yes iostream +=

repeat above steps yes built-in for

select steps yes built-in if

increment count yes iostream ++

divide doubles yes built-in /return a double yes built-in return

terminate program yes cstdlib exit()

Function 1 AlgorithmFunction 1 Algorithm0. Initialize sum to 0, count to 0.0. Initialize sum to 0, count to 0.1. Loop:1. Loop: a. Read a. Read scorescore.. b. If b. If scorescore < 0: terminate repetition. < 0: terminate repetition. c. Increment count.c. Increment count. d. Add score to sum.d. Add score to sum. End loop.End loop.2. If count > 02. If count > 0 Return sum / count.Return sum / count. ElseElse Display an error message and terminate the Display an error message and terminate the

program.program.

Function 1 CodingFunction 1 Coding#include <cstdlib> // exit() double ReadAndAverage(){ double score, sum = 0.0; int count = 0;

for (;;) { cout << “Enter a test score (-1 to quit): “; cin >> score; if (score < 0) break; // test for sentinel count++; sum += score; }

if (count > 0) return sum / count; else { cerr << “\n* no scores to average!\n” << endl; exit(1); }}

Function 2 BehaviorFunction 2 Behavior

Our function should receive from its Our function should receive from its caller an average. If that average is caller an average. If that average is less than 60, it should return a failing less than 60, it should return a failing grade; otherwise, it should return a grade; otherwise, it should return a passing grade.passing grade.

Function 2 ObjectsFunction 2 Objects

Description Type Kind NameDescription Type Kind Name

failing grade char constant ‘F’

average double varying avg

passing grade char constant ‘A’

Function 2 OperationsFunction 2 Operations

Description Predefined? Library? NameDescription Predefined? Library? Name

receive double yes built-in --

return a char yes built-in returnselect from among yes built-in if different returns

Function 2 AlgorithmFunction 2 Algorithm

0. Receive 0. Receive avgavg from caller. from caller.

1. If 1. If avgavg < 60: < 60:Return ‘F’.Return ‘F’.

ElseElseReturn ‘P’.Return ‘P’.

Function 2 CodingFunction 2 Codingchar PassFailGrade(double avg){

if (avg < 60) return ‘F’; else return ‘P’;}

DiscussionDiscussion

ReadAndAverage() and PassFailGrade() ReadAndAverage() and PassFailGrade() are sufficiently useful that it is are sufficiently useful that it is probably worth storing them in a probably worth storing them in a library (e.g., grading).library (e.g., grading).

Once we have functions for each Once we have functions for each operation that is not predefined, we operation that is not predefined, we can encode the algorithm that solves can encode the algorithm that solves our problem.our problem.

CodingCoding#include <iostream>

#include “grading.h” // ReadAndAverage(), PassFailGrade()

int main(){ cout << “\nThis program reads a sequence of test scores” << “\n and computes their pass-fail grade.\n”;

double average = ReadAndAverage(); char grade = PassFailGrade(average);

cout << “\nThe average is “ << average << “\n and the grade is “ << grade << endl;}

TestingTesting

This program reads a sequence of test scores and computes their pass-fail grade.

Enter a score: 65Enter a score: 55Enter a score: 75Enter a score: -1

The average is 65 and the grade is P

.

.

.

Summary (i)Summary (i)

The C++ for loop lets you The C++ for loop lets you repeatrepeat a block of a block of statements a specified number of times.statements a specified number of times.

Patterns:Patterns:for (int count = Start; count <= Stop; count++)

Statements

for (;;){

StatementList1if (Condition) break;StatementList2

}

These permit These permit repetitive executionrepetitive execution of of statements.statements.

Summary (ii)Summary (ii)

The C++ if statement lets you The C++ if statement lets you selectselect from from among two statements.among two statements.

Pattern:Pattern: if (BooleanExpression)

Statement1[else

Statement2]

This permits This permits selective executionselective execution of of statements.statements.


Recommended