designing programs and the role of functions objectives solve a few simple programs, emphasizing the...
TRANSCRIPT
Designing Programs and the Role of Functions
Objectives
Solve a few simple programs, emphasizing the steps involved in the process.
Introduce the concept of a function.
Understand
how to call a function w/o parameters
how to write a simple function w/o parameters
how to use input parameters for a function
how to return a result from a function
Sample Problem. Trip Cost.PROBLEM:
Input :
1.miles to travel 2.speed to drive
3.miles/gallon of car 4.capacity of tank
5.gas cost/gallon 6.other expense per stop
7.time per stop
Process :
Assume that you stop only to refill for gas.
On each stop, you will buy items which are
not gas items (drinks etc in value 6).
In addition you will incur delays at each stop(value 7).
Calculate values requested.
Output :
number of stops at gas stations
money spent on gas, non-gas items and total cost
time required to make the trip
Algorithm:
1. Read values
2. Calculate total number of gallons required
3. Calculate mileage expected for a tank. Assume you can pull into a station on the FUMES.
4. Calculate tanks expected for the trip.
Assume the tank is initially empty and you begin at the station.
5. Calculate cost of the gas
6. Calculate cost of other expenses for all stops (from answer to part 3)
7. Calculate total cost of the trip for gas and non-gas
8. Calculate time expected to make the trip excluding stops
9. Calculate time required for the stops
10. Calculate total time for the trip
#include <iostream.h>
#include <math.h> // for ceil function Fig. 3.2 p. 147
void main()
{ float total_miles, speed, mpg, gallons_in_tank, cost_p_gallon, other_cost_p_stop, time_p_stop;
int fillups_needed;
float gallons_reqd, miles_p_tank, cost_of_gas, other_cost,
total_cost, time_drive, time_for_stops, total_time;
cout << “Enter input information” << endl; // yuck
cin >> total_miles >> speed >> mpg;
cin >> gallons_in_tank >> cost_p_gallon;
cin >> other_cost_p_stop >> time_p_stop;
// GALLONS REQUIRED
gallons_reqd = total_miles / mpg;
// mileage per tank
miles_p_tank = mpg * gallons_in_tank;
// tanks for trip
fillups_needed = ceil(total_miles / miles_p_tank);
// cost of gas
cost_of_gas = gallons_reqd * cost_p_gallon;
(Cont.)
// cost of drinks etc
other_cost = fillups_needed * other_cost_p_stop;
// total_cost
total_cost = cost_of_gas + other_cost;
// time for the trip without stops
time_drive = total_miles / speed;
// time for stops
time_for_stops = fillups_needed * time_p_stop;
// total_time
total_time = time_drive + time_for_stops;
// cout statements
cout << "The trip is " << total_miles << " miles long.\n";
cout << "It will cost " << cost_of_gas << " for gas,\n";
cout << " and " << other_cost << " for other things.\n";
cout << "Total cost->" << total_cost;
cout << "Total time->" << total_time;
}
The PRIMARY purpose of FUNCTIONS
Functions simplify the interface!
Simpler Interfaces Make Our Job Easier!
First examples are NOT typicalWe'll start with very simple ones and BUILD
Examples in the text are functions which OUTPUT.
Consider the program and drawing.
#include <iostream.h>
void draw_circle()
{ cout << " * " << endl; *
cout << "* *" << endl; * *
cout << " * * " << endl; * *
}
void draw_box()
{ cout << "*****" << endl; *****
cout << "* *" << endl; * *
cout << "*****" << endl; *****
} *
void main () * *
{ // function prototypes * *
void draw_circle(); *****
void draw_box(); * *
// calls to functions *****
draw_circle(); *
draw_box(); * *
draw_circle(); * *
} // functions definions would follow
#include <iostream.h>void draw_circle(){ cout << " * " << endl; *
cout << "* *" << endl; * *cout << " * * " << endl; * *
}void draw_box(){ cout << "*****" << endl; *****
cout << "* *" << endl; * *cout << "*****" << endl; *****
} *void main () * *{ // function prototypes * *
void draw_circle(); *****void draw_box(); * * // calls to functions *****draw_circle(); * draw_box(); * *draw_circle(); * *
} // functions definions would follow
How do you trace the program flow(control)?
This is a little tricky. Think of a boomerang.The function always returns to the place from
which it was called!
#include <iostream.h>void draw_circle(){ cout << " * " << endl; *
cout << "* *" << endl; * *cout << " * * " << endl; * *
}void draw_box(){ cout << "*****" << endl; *****
cout << "* *" << endl; * *cout << "*****" << endl; *****
} *void main () * *{ // function prototypes * *
void draw_circle(); *****void draw_box(); * * // calls to functions *****draw_circle(); * draw_box(); * *draw_circle(); * *
} // functions definions would follow
How do you trace the program flow(control)?
This is a little tricky. Think of a boomerang.The function always returns to the place from
which it was called!
#include <iostream.h>void draw_circle(){ cout << " * " << endl; *
cout << "* *" << endl; * *cout << " * * " << endl; * *
}void draw_box(){ cout << "*****" << endl; *****
cout << "* *" << endl; * *cout << "*****" << endl; *****
} *void main () * *{ // function prototypes * *
void draw_circle(); *****void draw_box(); * * // calls to functions *****draw_circle(); * draw_box(); * *draw_circle(); * *
} // functions definions would follow
How do you trace the program flow(control)?
This is a little tricky. Think of a boomerang.The function always returns to the place from
which it was called!
Compare the program with a version which does NOT use FUNCTIONS
Note the CLARITY of what the programmer is trying to accomplish.
We have further aggravated the problem by avoiding the use of comments.
How LONG would it take to figure it out?
#include <iostream.h>
void main ()
{ cout << " * " << endl;
cout << "* *" << endl;
cout << " * * " << endl;
cout << "*****" << endl;
cout << "* *" << endl;
cout << "*****" << endl;
cout << " * " << endl;
cout << "* *" << endl;
cout << " * * " << endl;
}
REUSABILITY
Once we write the function we can create many figures which use boxes and circles!
The problem with software reusability is that
what we think is GENERAL tends NOT TO BE SO.
Consider drawing ***** *****
* * * *
***** *****
THIS WON’T WORK!
draw_box();
draw_box();
It will draw boxes VERTICALLY.
True REUSABILITY takes lots of practice and FORESIGHT. OOP/OOD helps.
Functions with PARAMETERS
As you design programs think of a function as a LITTLE PROGRAM
INPUT -> PROCESS -> OUTPUT
Example:
From the gas problem write a function to determine the mileage expected from a tank of gas.
mpg -> multiply -> mp_tank
gallons_in_tank
// DEFINITION OF THE FUNCTION
float mp_tank ( float mpg, float gallons_in_tank )
{
return mpg * gallons_in_tank;
}
// USE OF THE FUNCTION
// replace the old assignment statement with
miles_p_tank = mp_tank( mpg, gallons_in_tank);
// instead of
// miles_p_tank = mpg * gallons_in_tank;
Formal vs Actual PARAMETERS
Why do we want the added confusion?
Example: calculating the area of a circle from the radius// function definition
// input: radius (float)
// output: area of a circle with that radius
float area_of_circle( float r)
{
return (3.14159 * r * r );
}
What happens when you use it?
We like them to be REUSABLE.
We want to find the area of DIFFERENT circles.
We want to use the function in different ways.
cout <<area_of_circle(10.5); //radius from constant
x = 2.3;
cout << area_of_circle(x); //radius from x
y = 77.9;
z = area_of_circle(y); //radius from y
We want Formal and Actual to be different!
Formal Parameter r
Actual Parameters 10.5xy
Where does all of this stuff GO?
Two basic choices:
1. In the same program
example fig. 3.4 p. 151/152
2. Put the functions in a separate file and use include.
There's a lot more to this. We'll do it later!
We choose “in the same program”..
the SIMPLER one!
General Structure
#include <system files> // METHOD 1
// function definitions
void main ()
{//no prototypes needed for functions defined above
// place any variable and const declarations
// place any executable statements
}
OR
#include <system files> // METHOD 2
// PROTOTYPES NEEDED for functions defined BELOW
void main ()
{ // place any variable and const declarations
// place any executable statements
}
// function definitions
General Structure (cont.)OR
// a file with function definitions only
// assume it is named myfunct.C
// a file containing ONLY the prototype
// assume it is named myfunct.h
#include <system files> // METHOD 3
#include "myfunct.h"
void main ()
{//prototypes for functions in myfunct.h not here
// place any variable and const declarations
// place any executable statements
}
Advantages of Methods of Organization
Methods 1 and 2.
No significant difference.
Method 1 requires NO prototype.
Method 3.
It is more complicated to set up BUT...
Allows separation of the code to actually do the function from the interface.
-> author can distribute object and .h without giving up the source
-> you can compile the library ONCE and use .h to incorporate calls
-> you can redefine the actual code and update other programs to relink as long as interface is the same
Are We Through With Parameters?
This is NOT the complete story!
You have only seen cases of
1. NO INPUT and NO RETURNED VALUE (void)
2. Using INPUTS and A RETURNED VALUE
Examples of combinations for later:
1. NO INPUT and a single output
2. Multiple OUTPUTS (???)
3. Changing the value of a parameter
RULES FOR NOW1. When passing parameters, be sure the parameters in the procedure and in the call are
typed the same (int, float, etc.)
2. Also make sure they agree in number and position.
3. Place functions after the main routine.
4. Include a PROTOTYPE for the function where it is called. (Method 2)
Centuries Top 10 Interfaces
• Loudspeaker• Touch-tone telephone• Steering Wheel• Magnetic-stripe card• Traffic light
• Remote control• Cathode-ray tube• Liquid crystal display• Mouse• Barcode scanner
According to MIT Technology ReviewNov/Dec 1999