Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | gertrude-barton |
View: | 212 times |
Download: | 0 times |
Lecture 9: Top-Down Design with Functions
COS120 Software Development Using C++ AUBG, COS dept
2
Lecture Contents:
Top-Down Design and step-wise refinement with structure charts
Basics of functions. General form of a function definition
Functions topics: prototype, call, definition Systems defined and user defined functions The minimal C++ function Functions with multiple arguments
3
Top-Down design
There exist problems whose solving algorithms are too complicated, more complex than those already solved. Then developer breaks up problem into sub problems to solve and develop program solution. If necessary some sub problems are to be broken up into sub sub problems and so on.
The process described is called Top-Down Design or step-wise refinement and is being illustrated using structure charts.
4
Basics of functions:
“Properly designed functions permit to ignore how a job’s done. Knowing what is done is sufficient.”
B.Kernighan & D.Ritchie
Most important reasons to use functions:
1. Dividing a program into functions is one of the major principles of structured programming.
2. Using functions results in reduced program size.
5
Basics of functions:
“A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation. ”
B.Kernighan & D.Ritchie
Usually functions are specified to be called many times.
You can see often a short function defined and called only once, just because it clarifies some piece of code.
6
Details on functions
Three important topics when dealing with functions:
prototype (signature) statement function call statement function definition (includes function
head or function title followed by a function body – compound statement surrounded in curly braces)
7
Syntax: functions with no argument(s) and no return value
Prototype statement: void fname(void);
Call statement: fname( );
Function Definition: void fname(void){ <local declarations> <executable
statements>}
8
Syntax: functions with argument(s) and no return value
Prototype: void fname(<formal parameters declaration list>);
Call: fname(<list of actual arguments>);
Definition:void fname(<formal parameters declaration list>){
<local variable declarations><executable statements>
}
9
Syntax: functions with argument(s) and return value
Prototype: ftype fname(<formal parameters declaration list>);
Call: res = fname(<list of actual arguments>);cout << fname(<list of actual arguments>);
Definition:ftype fname(<formal parameters declaration list>){
<local variable declarations><executable statements>return (<expression>);
}
10
The minimal C/C++ function
Minimal C++ function in 3 versions: it does nothing and returns “almost” nothing.
dummy() { }
dummy() { return 0; }
void dummy(void) { }
11
Functions with multiple arguments
The accent:Formal parameter: variableFormal parameters declaration list: parameters, i.e. variables,
separated by comma
Actual argument: literal, variable, fun. call, expressionList of actual arguments: arguments, separated by comma.
Example: function to compute (return) the average of two integers on next slide
12
Function to return average of two integers
Prototype in two versions:
double ave(int num1, int num2);
double ave(int, int);
13
Function to return average of two integers
Function definition in two versions:
// 1st versiondouble ave(int num1, int num2){ double result; result = (num1 + num2) / 2.; return result;}
OR
14
Function to return average of two integers
Function definition in two versions:
OR
// 2nd versiondouble ave(int num1, int num2){ return (num1 + num2) / 2.;}
15
Function to return average of two integers
Function definition in two versions:double ave(int num1, int num2) // 1st version { double result; result = (num1 + num2) / 2.; return result;}
ORdouble ave(int num1, int num2) // 2nd version{ return (num1 + num2) / 2.;}
16
Function to return average of two integers
Function call in variety of versions: Actual arguments: two literals
// value returned from ave directly displayed cout << endl << ave(30, 40);
// value returned from ave assigned to variable for use
double res; res = ave(50, 60); cout<<‘\n’<<“Average value is = “<< res;
17
Function to return average of two integers
Function call in variety of versions: Actual arguments: two variables initialized// value returned from ave directly displayed int a=60, b=40; cout << endl << ave(a, b);
// value returned from ave assigned to variable for use
double res; int a=650, b=420; res = ave(a, b); cout << ‘\n’ << “Average value is = “ << res;
18
Function to return average of two integers
Function call in variety of versions: Actual arguments: two variables loaded at runtime// value returned from ave directly displayed int a, b; cout <<“\nEnter 2 integers:”; cin >> a >> b; cout << endl << ave(a, b);
// value returned from ave assigned to variable for use
double res; int a, b; cout <<“\nEnter data:”; cin >> a >> b; res = ave(a, b); cout << ‘\n’ << “Average value is = “ << res;
19
Task to train functions
Create and test a function to return average of three integers
Create and test a function to return average of five integers
Create and test a function to return average of seven integers– Solution as a single function with 7 parameters– Solution based on a function with 2 only parameters – Reuse
functions ave2(p1,p2) and ave5(p1,p2,p3,p4,p5)
Attention: Next slide of high importanceRead carefully, think, understand
&
Do not forget what is written!!!
21
The Moral on function calling statement
If a function does not return a value, it’s called in the following context as a statement:
<fname>( <optional list of arguments> );
DrawHouse( );NumInBox(35.68);
If a function does return a value, it’s called in two other contexts: – As an operand of cout statement to display the value returned
cout << endl << ave(30,50);– As on operand in the right side of assignment statement
res = ave(60,70)*5 + pol/ave(56,88);
22
Function to return average of two integers
Function call in variety of versions:Actual arguments:
– Literal and variable– ave(30, x);– Expression composed of literal and variables– ave(x+y, b-4);– Run-time library function calls– ave(int(sqrt(6+p)),(int)exp(var));
23
Previous lecture reminder
Title:
Top-Down Design Using Functions
Source: Friedman/Koffman, Chapter 03
Have a quick look at next approx 60 slides to refresh your knowledge on functions
Top-Down Design with Functions and Classes
Chapter 3
25
3.2 Library Functions
– Goal of Structured Programming• Error free code
– Reusability• Don’t reinvent the wheel
– C ++ provides collection of functions
– Organized in Libraries• Library examples Table 3.1
26
C++ Math Library
– Functions in the Math library• sqrt cos sinpow
• Examples Table 3.1
– Function use in Assignmentsy = sqrt(x);
sqrt is function name
x is function argument
– Activated by a “function call”
– Result of execution is assigned to variable y
27
C++ Math Library (cont)
Function sqrt as a “black box”
Square rootcomputation
X is 16.0 Result is 4.0
28
C++ Library Functions
– We can effectively utilize existing functions by learning to read function prototypes with the preconditions and postconditions.
– Example prototype (or signature) double sqrt(double x); // PRE: x >= 0.0 // POST: Returns the square root of x.
29
Preconditions and Postconditions
– Comments that represents a contract between the implementor of a function and the user (client) of that function.
– We'll look at two such comments:• Precondition: What the function requires.• Postcondition: What the function will do if
the precondition is met.
30
Preconditions and Postconditions
– The preconditions are the circumstances that must be true before the function can successfully fulfill the promised postconditions.
– Example (Precondition abbreviates to PRE:double sqrt(double x);
// PRE: x >= 0
// POST: Returns square root of argument X
31
SquareRoot.cpp
// File: squareRoot.cpp// Performs three square root computations
#include <cmath> // sqrt function#include <iostream> // i/o functionsusing namespace std;
int main(){ float first; float second; float answer;
32
SquareRoot.cpp
// Get first number and display its square root. cout << "Enter the first number: "; cin >> first; answer = sqrt(first); cout << "The square root of the first
number is " << answer << endl;
// Get second number and display its square root. cout << "Enter the second number: "; cin >> second; answer = sqrt(second); cout << "The square root of the second
number is " << answer << endl;
33
SquareRoot.cpp
// Display the square root of the sum of first// and second.
answer = sqrt(first + second); cout << "The square root of the sum of
both numbers is " << answer << endl;
return 0;}
34
SquareRoot.cpp
Program Output
Enter the first number: 9The square root of the first number is 3Enter the second number: 16The square root of the second number is 4The square root of the sum of both numbers is 5
35
3.3 Top-Down Design and Structure Charts
D raw aC irc le
D rawin te rsec tin g
lin es
D raw ab ase
D raw aTrian g le
D rawin te rsec tin g
lin es
D raw afig u re
Original Problem
Detailed
subproblems
Level 0
Level 1
Level 2
36
How to continue?
Next 35 slides (37-70) contain general purpose info on functions already discussed in previous two lectures
You may read them as a refreshing reminder OR
You may skip them jumping to slide titled “3.7 Extending C++ through Classes”
37
3.4 Functions without Arguments
– Functions used in Top-Down Design– main() is just a function
• called by OS
– C++ program is a collection of Functions• top level function is called the main()• lower level functions
– User Defined or Libraries– Example StkFigMn.cpp
38
StickFigure.cpp
// File: stickFigure.cpp// Draws a stick figure
#include <iostream>
using namespace std;
// Functions used ...
void drawCircle(); // Draws a circlevoid drawTriangle(); // Draws a trianglevoid drawIntersect(); // Draws intersecting linesvoid drawBase(); // Draws a horizontal line
39
StickFigure.cpp
int main(){// Draw a circle. drawCircle();
// Draw a triangle. drawTriangle();
// Draw intersecting lines. drawIntersect();
return 0;}
40
Function Calls
– We can call a function and get results without knowing the implementation of that function.• pow(x, y) returns x to the yth power.
– For now, we need not know exactly how a function is implemented.
– However, we do need to know how to use the function.
41
Function Calls
– This general form of a function call:
function-name ( optional argument-list );– Example function call:
drawCircle ();– The function name is drawCircle – No arguments to the function
42
Function Prototype
– This general form of a function prototype:
type function-name ( optional argument-list );
– Example function prototype:
void skipThree ();
– Type
• int - float - char
– Name
– ( );
– Descriptive comment
43
Function Definition
– General form of a function definition:
type function-name ( optional argument-list )
{
local-declarations - function body
executable-statements
}– Example function definition:
void drawTriangle ()
44
Function Definition
void drawTriangle()
{
// Draw a triangle.
drawIntersect();
drawBase();
}
function header
function body
45
StickFigure.cpp
// Draws a circlevoid drawCircle(){ cout << " * " << endl; cout << " * *" << endl; cout << " * * " << endl;} // end drawCircle
46
StickFigure.cpp
void drawCircleChar(char symbol){ cout << " " << symbol << " " << endl; cout << " " << symbol << " " << symbol <<
endl; cout << " " << symbol << " " << symbol <<
endl;}
// Draws a trianglevoid drawTriangle(){ drawIntersect(); drawBase();}
47
StickFigure.cpp
// Draws intersecting lines
void drawIntersect(){ cout << " / \\ " << endl; cout << " / \\ " << endl; cout << " / \\" << endl;}
// draws a horizontal linevoid drawBase(){ cout << " -------" << endl;}
48
Order of Execution
int main()
{
drawCircle();
drawTriangle();
drawIntersect();
return 0;
}
void drawCircle()
{
cout << “ * “ << endl;
cout << “ * * “ << endl;
cout << “ * * “ << endl;
}
49
Function Advantages
– Program team on large project
– Simplify tasks
– Each Function is a separate unit
– Top-down approach
– Procedural abstraction
– Information hiding
– Reuse (drawTriangle)
50
Abstraction
– Abstraction:• Refers to the act of ignoring details to
concentrate on essentials.• Allows us to use complicated things with
little effort (CD players, automobiles, computers).
51
Displaying User Instructions
We still have not covered passing in and out of a function
Following example shows displaying info– instruct(); function call in main
52
Instruct.cpp
// DISPLAYS INSTRUCTIONS TO USER OF AREA/CIRCUMFERENCE PROGRAM
void instruct (){ cout << "This program computes the area and " << endl; cout << "circumference of a circle. " << endl << endl; cout << "To use this program, enter radius of the " << endl; cout << "circle after the prompt" << endl; cout << "Enter the circle radius: " << endl << endl; cout << "The circumference will be computed in the ” << endl; cout << "units of measurement as radius. The area " << endl; cout << "will be computed in thesame units squared." << endl;}
53
Program Output
This program computes the area and circumference of a circle.
To use this program, enter the radius of the circle after the prompt
Enter the circle radius:
The circumference will be computed in the same units of measurement as the radius. The area will be computed in the same units squared.
54
3.5 Functions with Input Arguments
– Functions used like building blocks
– Build systems one functions at a time• Stereo Components
– Use function return values and arguments to communicate between functions
– Discuss AreaMain.cpp• Flow of arguments and returns
55
Function Call
Form: fname(actual arg list);
Example: scale(3.0, z);
56
Function Return
Functions must return a value unless declared as void
Form: return expression;
Example: return x * y;
57
Function Definition
Form: type fname (formal arg list){
function body}
Example: float scale(float x, int n){
float scaleFactor;scaleFactor = pow(10, n);
return (x * scaleFactor);}
58
Function Prototype
Form: type fname (formal arg type list);
Example: float scale (float x, int n);
59
TestScale.cpp
// File testScale.cpp// Tests function scale. #include <iostream>#include <cmath>
using namespace std;
// Function prototype float scale(float, int);
int main(){
60
TestScale.cpp
float num1; int num2;
// Get values for num1 and num2 cout << "Enter a real number: "; cin >> num1; cout << "Enter an integer: "; cin >> num2;
// Call scale and display result. cout << "Result of call to function scale
is " << scale(num1, num2) << endl;
return 0;}
61
TestScale.cpp
float scale(float x, int n){ float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor);}
62
Argument / Parameter List Correspondence
– Functions can have more than 1 arg– Correspondence between Actual & Formal
arguments
Function call scale (3.0, z);
Actual Argument Formal Parameter
3.0 x
z n
63
Argument / Parameter List Correspondence
float scale(float x, int n)
{float scaleFactor;
scaleFactor = pow(10, n);return (x * scaleFactor);
}
64
Argument / Parameter List Correspondence
Function call scale (x + 2.0, y);
Actual Argument Formal Parameter
x + 2.0 x
y y
65
Argument / Parameter List Correspondence
Function call scale (y, x);
Actual Argument Formal Parameter
y x
x y
Watch for type matches in formal parameters and actual arguments
66
Key Points
The substitution of the value of an actual argument in a function call for its corresponding formal argument is strictly positional. That is, the value of the first actual argument is substituted for the first formal argument; the second and so on
67
Key Points
The names of these corresponding pairs of arguments are no consequence in the substitution process. The names may be different, or they may be the same.
The substituted value is used in place of the formal argument at each point where that argument appears in the called function.
68
3.6 Scope of Names
Variable declared in a function has a local scope within the function
Same for variables declared in the main Variable declared before main is global
scope– Call anywhere in program
Functions declared globally
69
Scope of Names
Positional correspondence Type consistent is key because of positional
correspondence– Argument types– Return types
70
Scope of Names
Type of a value returned by a called function must be consistent with the type expected by the caller as identified in the prototype
Type of an actual argument in a function call must be consistent with the type of its corresponding formal argument
71
3.7 Extending C++ through Classes
– Discuss classes• String class part of compiler
– #include <string>
72
String Class
Declaring string objects Reading & Displaying strings Assignment & Concatenation Operator Overloading Dot Notation Member Functions Object Assignments
73
Declaring string Objects
A number of ways to declare
string firstName, lastName;
string wholeName;
string greeting = “Hello “;
74
Reading & Displaying string Objects
Use extraction operator >> and the stream cin for input–cin >> firstName;
Use insertion operator << and the stream cout for output– cout << greeting << wholeName << endl;
75
Reading & Displaying string Objects
getline(cin, lastName, ‘\n’);
reads all characters typed in from the keyboard up to the new line into the string object
76
Reading & Displaying string Objects
Other valid calls:
getline (cin, lastName);
getline (cin, lastName, ‘ ’);
getline (cin, lastName, ‘\t’);
getline (cin, lastName, ‘e’);
77
StringOperations.cpp
// ILLUSTRATES STRING OPERATIONS#include <iostream>#include <string>using namespace std;
int main (){
string firstName, lastName; string wholeName; string greeting = "Hello ";
cout << "Enter your first name: "; cin >> firstName;
78
StringOperations.cpp
cout << "Enter your last name: "; cin >> lastName;
// Join names in whole name wholeName = firstName + " " +
lastName;
// Display results cout << greeting << wholeName << '!' << endl; cout << "You have " <<
(wholeName.length () - 1) << " letters in your name."
<< endl;
79
StringOperations.cpp
// Display initials cout << "Your initials are "
<< (firstName.at(0)) << (lastName.at(0)) <<
endl;return 0;
}
80
StringOperations.cpp
Program outputEnter your first name: Caryn
Enter your last name: Jackson
Hello Caryn Jackson!
You have 12 letters in your name.
Your initials are CJ
81
Assignment
Stores the first and last name– wholeName = firstName + “ “ + lastName;
Concatenation– + joins the two objects together
“ “ for string values not ‘ ‘
82
Operator Overloading
+ normally means addition but with strings it means concatenation
The + can take on many meanings– Operator Overloading– C++ can have multi meanings to 1 operator– >> and << are overloaded operators, see next slide– * / - == = all can be overloaded
83
Operator Overloading
<< originally means shift left >> originally means shift right Here are more details on SHIFT operators:
84
Dot Notation
Dot notation used to call an objects member functions
wholeName.length();– Applies member function length to string object
wholeName– Function returns the objects length– Table 3.3 lists some additional functions
85
Header Files and Implementation Files
Header file (.h)– File containing information that C++ needs to
compile a program that accesses a user-defined class
Implementation file (.cpp)– File containing the C++ code for the operators
of a user defined class
86
3.8 Common Programming Errors
– Semicolon in Function Prototype (Declaration)– Inconsistencies in Number of Arguments
• Too few arguments in a call
• Too many arguments in a call
• Incorrect number of arguments in call
• Extra argument in call
– Argument Mismatch• Correct position (formal params & actual args)
87
Common Programming Errors
– Function Prototype & Definition Mismatches• Both are the same except for the ;
– Return Statements• “Return value expected”• “Function should return value”
– Missing Object Name in Call to Member Function
– Missing #include– Type Mismatches
88
Exercise 9.1
Define a function and Build a program: to compute the volume of a pool
Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation
89
Exercise 9.2
Define a function and Build a program: To return the product of a real and an
integer using the formula m*10n
Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation
90
Exercise 9.3
Define a function and Build a program: to solve the Finding dollar value of coins
problem
Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation
91
Exercise 9.4
Define a function and Build a program: to solve the Feet/Inches to Meters
conversion problem
Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation
92
Homework 2
Paper record to be presented before the end of next class
Tasks:– See .doc file.
93
reminder
Quiz #2
on
Skills in C++ Functions
will take place next lesson
94
Before lecture end
Lecture:
Top-Down Design using Functions
More to read:
Friedman/Koffman, Chapter 03
95
Thank You
For
Your Attention!