Programming and Problem Solving with C++, 2/e

Download Report

Transcript Programming and Problem Solving with C++, 2/e

Further Control Structures



I will go over some important topics today.
Loops and conditionals are essential for ones
development in any programming language.
We will look at the three types of looping
mechanisms




for
do-while
while
We will also look again at the if statement only
if it is required.
1
Week 4 Topics

Switch Statement for Multi-way Branching







Can be achieved with an if statement
This was previously looked at
We have to be careful with the “fall through”
mechanism however.
Do-While Statement for Looping
For Statement for Looping
Using break and continue statements
These are used predominantly with the switch
statement
2
Display a menu
Simple Menus
1.
2.
3.
4.
Program displays a menu of choices
User enters a choice
Program responds to choice
Go back to to 1
3
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main( ) {
function prototype consisting of
<type> function name (types of parameters);
return 0;
}
So void here means no return type or parameters
expected. It is not required to use void here.
4
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main() {
Definition:
like a mini program
or sub program
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1.
Man United” << endl;
cout << “ 2.
Chelsea” << endl;
cout << “ 3.
Arsenal” << endl;
cout << “ 4.
Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
5
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main() {
int response;
DisplayMenu();
Function call
from within
main()
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1.
Man United” << endl;
cout << “ 2.
Chelsea” << endl;
cout << “ 3.
Arsenal” << endl;
cout << “ 4.
Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
Prompt
6
User enters choice
Prompt was part of function DisplayMenu
 use cin to get a response from user.
 The function is invoked by a call from
another function, in this case the calling
function is main()
 The call is just a writing of the function
name in this case, with no parameters
passed to this function

7
Display a menu and Get response
#include <iostream>
void DisplayMenu(void);
int main() {
int response;
Get response
DisplayMenu();
cin >> response;
return 0;
}
void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1.
Man United” << endl;
cout << “ 2.
Chelsea” << endl;
cout << “ 3.
Arsenal” << endl;
cout << “4.
Quit” << endl;
cout << endl;
cout << “Please choose 1, 2 or 3 : “;
}
8
Process the response
by using the switch statement
9
What is
the switch Statement
Similar to the if statement
 Can list any number of branches
 Used in place of nested if statements
 Used only with integer expressions
(true/false or int or char)
 Avoids confusion of deeply nested if
statements

10
The switch Statement
Syntax
switch (expression)
{
case value1:
case value2:
default:
statement1;
break;
statement2;
break;
case valueN: statementN;
break;
statement;
}
expression must return an integer value, i.e. be an integer
The switch Statement
with char expression
switch (choice)
{
case 1:
cout <<
break;
case 2:
cout <<
break
case 3:
cout <<
break;
case 4:
cout <<
}
//next statement
“The greatest ” << endl;
“Exciting team ”<< endl;
“Boring ” << endl;
“Bye Bye” << endl;
What is the purpose of the break statement?
The break Statement prevents “fall through”
it makes the computer jump out of the current
block, recall that the switch statement will execute
all statements below the point of entering the
statement. This can be a problem.
The switch Statement illustrate fall
through again
switch (choice){
case 1:
cout <<
case 2:
cout <<
case 3:
cout <<
case 4:
cout <<
}
“The greatest ” << endl;
“Exciting team ”<< endl;
“Boring ” << endl;
“Bye Bye << endl;
The switch Statement
What will be the output when the user enters 1?
The greatest
Exciting team
Boring
Bye Bye
The switch Statement
What will be the output when the user enters 2?
Exciting team
Boring
Bye Bye
The switch Statement
What will be the output when the user enters 3?
Boring
Bye Bye
The switch Statement
What will be the output when the user enters 4?
Bye Bye
Classic use of switch Statements:
for Menu processing
* * * * Menu * * * *
1. Man United
2. Chelsea
3. Arsenal
4. Quit
Choose either 1, 2, 3 or 4:
Example program to Demo
#include <iostream> //see displaymenu3.cpp
Using namespace std;
void DisplayMenu(void);
int main(void) {
int choice;
DisplayMenu();
cin >> choice;
switch (choice)
case 1: cout <<
case 2: cout <<
case 3: cout <<
case 4: cout <<
};
return 0;
{
“The greatest“ << endl;
“Exciting team“ << endl;
“Boring“ << endl;
“Bye Bye << endl;
}
void DisplayMenu(void) {
cout << "*********** MENU **************\n";
cout <<endl;
cout << " 1.
Man United" << endl;
cout << " 2.
Chelsea" << endl;
cout << " 3.
Arsenal" << endl;
cout << endl;
cout << "Please choose 1, 2 or 3 : ";
}
20
The switch Default Statement captures
errors or perform default action
e.g. if user enter any other number
switch (choice){
case 1:
cout << “The greatest ” << endl;
break;
case 2:
cout << “Exciting team ”<< endl;
break;
case 3:
cout << “Boring ” << endl;
break;
case 4:
cout << “Bye Bye “ << endl;
break;
default: “Incorrect choice” << endl;
}
Nested Switch Statements
For example:
switch( CarType )
{
case MONDEO:
switch( EngineCapacity)
{
case 1500:cout << “This is underpowered “;
break;
case 1800: cout << “This is just right”;
break;
case 2000: cout<<“This is expensive to run”;
}; //closes second switch
case FIESTA: break;
default: cout << “Unknown model”;
} //closes first switch
22
Problems with switch

Strange rules, once a condition is tested true
execution proceeds until break or end of
switch.




Control “falls through” the switch
Get in the habit of always putting breaks in and
putting a default condition in.
Less satisfactory to use where floats or
Boolean expressions are tested.
Putting in semi colon ‘;’after case rather than
colon ‘:’
23
Recall Purpose of
Loops/Repetition
To apply the same steps again and
again to a block of statements.
 Recall a block of statement is one or
more statement, block usually defined
by braces { … } with syntactically correct
statements inside.

24
Most Common Uses of Loops
You should master all these!








For counting
For accumulating, i.e. summing
For searching
For sorting
For displaying tables
For data entry – from files and users
For menu processing
For list processing
25
Types of loops
while
for
do..while
26
C/C++ Loop Structures

Pre-test (the test is made before entering
the loop)

while loops
– general purpose
– Event controlled (variable condition)

for loops
– When you know how many times (fixed condition)
– When you process arrays (more in later lectures)

Post-test (the test is done at the end of the
loop)

do … while loops
– When you do not know how many times, but you know
you need at least one pass.
27
– Data entry from users
Do-While Statement
Is a looping control structure in which the loop
condition is tested after each iteration of the
loop.
SYNTAX
do
{
Statement
} while (Expression) ; //note semi colon
Loop body statement can be a single statement or a block.
28
Function Using Do-While
void GetYesOrNo ( char response )
//see UseofFunction1.cpp
// Inputs a character from the user
// Postcondition:
response has been input
//
&& response == ‘y’ or ‘n’
{
do
{
cin >> response ;
// skips leading whitespace
if ( ( response != ‘y’ ) && ( response != ‘n’ ) )
cout << “Please type y or n : “ ;
} while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ;
}
29 29
Do-While Loop vs. While Loop



POST-TEST loop
(exit-condition)
The looping condition
is tested after
executing the loop
body.
Loop body is always
executed at least
once.



PRE-TEST loop
(entry-condition)
The looping condition
is tested before
executing the loop
body.
Loop body may not
be executed at all.
30
Do-While Loop
DO
Statement
WHILE
Expression
TRUE
FALSE
When the expression is tested and found to be false,
the loop is exited and control passes to the
statement that follows the do-while statement. 31
The for Statement Syntax
start condition
while condition
change expression
Example:
for (count=1; count < 7; count++)
{
cout << count << endl;
}
//next C++ statements;
The for Statement



Used as a counting loop
Used when we can work out in advance the
number of iterations, i.e. the number of times
that we want to loop around.
Semicolons separate the items in the for loop
block

There is no semi colon at the end of the for loop
definition at the beginning of the statement
A Simple Example
Create a table with a for loop
int num;
cout << "NUMBER\tSQUARE\tCUBE\n“;
cout << "------\t------\t----\n";
for (num = 1; num < 11; num++) {
cout << num << “\t“;
cout << num * num << “\t“;
cout << num * num * num<<“\n";
}//see useofFunction2.cpp
NUMBER
---------1
2
.
.
10
SQUARE
---------1
4
.
.
100
CUBE
-----1
8
.
.
1000
Use of the for loop
Please see the following files
 Harmonic.cpp
 BaselSeries.cpp
These are two very important series in
mathematics.

35
for and if Statements working
together.
Simple search for divisors
 Given an integer number find all the
numbers that divide exactly into it (including
1 and itself).

Think I can
use % operator
to find divisors

e.g. if number = 12, divisors are 1,2,3,4,6,12
Solution Design
1.
2.
Get the number from user
By starting with check number=1 and
finish with number (is this efficient?)
find the remainder of dividing number with
current check number
2. if remainder is 0 display current check
number as a divisor.
3. otherwise do not display anything
1.
37
Program fragment for finding divisors of an
integer
cout << “Enter an integer :”;
cin >> number;
for (j = 1; j <= number; j++)
{ if (number % j == 0)
{
cout << j << “ is a divisor of
“;
cout << number << endl;
}
}//see useofFunction3.cpp, this program
determines whether we have a perfect
number
38
Common errors in constructing
for Statements
for (j = 0, j < n, j = j + 3)
// commas used when semicolons needed
for (j = 0; j < n)
// three parts needed
for (j = 0; j >= 0; j++)
?????what is wrong here ?????
for (j=0, j=10; j++);
Infinite loops example 1
for (j=0; j>=0; j++) {
cout << j << endl;
}
What will happen here?
//see infiniteloop1.cpp
40
Loop design
Seven Loop Design Factors
1. What is the condition that ends the loop?
2. How should the condition be setup or
primed?
3. How should the condition be updated?
4. What processes are being repeated?
5. How do you set up the processes?
e.g. initialise event counters or accumulators
6.
How is the process updated?
e.g. update accumulators and counters
7.
What is the expected state of the program
at exit from loop?
41
Programming convention




Use of integers called i,j,k
You will see them all the time.
Most commonly used as loop control
variables
Conventionally used for counters



We will see later that counters often have a dual
use as array indices.
arrays to be discussed in later lectures
When you see i,j,k declared expect to see a
loop!
42
Example of Repetition
int n;
for ( int i = 1 ; i <= n ; i++ )
{
cout << i << “ Potato” << endl;
}
//see usefor1.cpp
// useofFunction5.cpp
global variable
uses an array as a
43
num
?
Example of Repetition
int n;
for ( int i = 1 ; i <= n ; i++ )
cout << i << “ Potato” << endl;
OUTPUT
44
num
Example of Repetition
1
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
45
num
Example of Repetition
1
int num;
true
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
46
num
Example of Repetition
1
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
47
num
Example of Repetition
2
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
48
num
Example of Repetition
2
int num;
true
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
49
num
Example of Repetition
2
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
50
num
Example of Repetition
3
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
51
num
Example of Repetition
3
int num;
true
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
52
num
Example of Repetition
3
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
3Potato
53
num
Example of Repetition
4
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
3Potato
54
num
Example of Repetition
4
int num;
false
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1Potato
2Potato
3Potato
55
num
Example of Repetition
4
int num;
false
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
When the loop control condition
is evaluated and has value false, the
loop is said to be “satisfied” and
control passes to the statement
following the for statement.
56
The output was:
1Potato
2Potato
3Potato
57
Nested Loops
Recall when a control structure is contained
within another control structure, the inner one
is said to be nested.
if ...
for...
for ...
for ...
You may have repetition within decision and
vice versa.
Nested Loops - Ex.1
for within for
Example //see nested1.cpp
int row,col;
for (row = 0; row < 5; row++)
{
cout << "\n" <<row; //throws a new line
for (col = 1; col <= 3; col++)
{
cout <<"\t" << col;
}
cout << "\t**"; //use of tab
}
CAUTION!
What is the output from this
loop?
int count;
for (count = 0; count < 10; count++) ;
{
cout << “*” ;
}
//see useforloop2.cpp
60
Infinite loop example 2
OUTPUT
*





no output from the for loop! Why?
the ; right after the ( ) means that the body
statement is a null statement
in general, the Body of the for loop is whatever
statement immediately follows the ( )
that statement can be a single statement, a
block, or a null statement
actually, the code outputs one * after the loop
completes its counting to 10
61
Nested Loops – Example 1
Output
0 1
1 1
2 1
3 1
4 1
2
2
2
2
2
3
3
3
3
3
variable row changes from
0 to 4
**
**
**
**
**
variable col changes from
1 to 3 for every time row
changes
Break Statement Revisited

break statement can be used with Switch or
any of the 3 looping structures

it causes an immediate exit from the Switch,
while, do-while, or for statement in which it
appears

if the break is inside nested structures,
control exits only the innermost structure
containing it
63
Continue Statement

is valid only within loops

terminates the current loop iteration, but
not the entire loop

in a for or while, continue causes the rest
of the body statement to be skipped--in a
for statement, the update is done

in a do-while, the exit condition is tested,
and if true, the next loop iteration is begun
64
The break Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
break;
cout << “j is “ << j<< ‘\n’;
}
cout << “We are out of the loop as j=70.\n”;
//see useBreak1.cpp
j is 50
j is 60
We are out of the loop as j=70.
The continue Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
continue; //skips the 70
cout << “j is “ << j<< ‘\n’;
}//see UseContinue1.cpp
cout << “We are out of the loop” << endl;
j is 50
j is 60
j is 80
We are out of the loop.
break and continue
while ( - - - )
{
statement 1;
if( - - - )
continue
statement 2;
}
statement 3;
while ( - - - )
{
statement 1;
if( - - - )
break
statement 2;
}
statement 3;
Break and Continue

Now see UseContinue1.cpp
68
Functions and Program Structure
A function is a ``black box'' that we have
locked part of our program into.
 The idea behind a function is that it
compartmentalizes part of the program,
and in particular, that the code within the
function has some useful properties:

69
More on functions




It performs some well-defined task, which
will be useful to other parts of the program.
It might be useful to other programs as well;
that is, we might be able to reuse it (and
without having to rewrite it).
The rest of the program does not have to
know the details of how the function is
implemented.
This can make the rest of the program
easier to think about.
70
More on functions



The function performs its task well.
It may be written to do a little more than is
required by the first program that calls it, with
the anticipation that the calling program (or
some other program) may later need the extra
functionality or improved performance.
It is important that a finished function do its
job well, otherwise there might be a
reluctance to call it, and it therefore might not
achieve the goal of reusability.
71
Functions


By placing the code to perform the useful task
into a function, and simply calling the function
in the other parts of the program where the
task must be performed, the rest of the
program becomes clearer.
Rather than having some large, complicated,
difficult-to-understand piece of code repeated
wherever the task is being performed, we
have a single simple function call, and the
name of the function reminds us which task is
being performed.
72
Functions


Since the rest of the program does not have
to know the details of how the function is
implemented, the rest of the program does not
care if the function is reimplemented later, in
some different way (as long as it continues to
perform its same task, of course!).
This means that one part of the program can
be rewritten, to improve performance or add a
new feature (or simply to fix a bug), without
having to rewrite the rest of the program.
73
More on functions


Functions are probably the most important
weapon in our battle against software
complexity.
You will want to learn when it is appropriate to
break processing out into functions (and also
when it is not), and how to set up function
interfaces to best achieve the qualities
mentioned above: reuseability, information
hiding, clarity, and maintainability.
74
4.1 Function Basics
So what defines a function?
 It has a name that you call it by, and a
list of zero or more arguments or
parameters that you hand to it for it to
act on or to direct its work; it has a body
containing the actual instructions
(statements).

75
Functions
For carrying out the task the function is
supposed to perform; and it may give
you back a return value, of a particular
type.
 Here is a very simple function, which
accepts one argument, multiplies it by 2,
and hands that value back to the
function that invoked it, i.e. To the
function that called it.
76

A simple function
int multbytwo(int x)
{
int retval;
//a local variable
retval = 2*x;
return retval;
}
77
Explaining the function



On the first line we see the return type of the
function (int), the name of the function
(multbytwo), and a list of the function's
arguments, enclosed in parentheses.
Each argument has both a name and a type;
multbytwo accepts one argument, of type int,
named x.
The name x is arbitrary, and is used only
within the definition of multbytwo.
78
Explaining the function
The caller of this function only needs to
know that a single argument of type int
is expected; the caller does not need to
know what name the function will use
internally to refer to that argument.
 In particular, the caller does not have to
pass the value of a variable named x.

79
Explaining the function



Next we see, surrounded by the familiar
braces { }, the body of the function itself.
This function consists of one declaration (of a
local variable retval) and two statements.
The first statement is a conventional
expression statement, which computes and
assigns a value to retval, and the second
statement is a return statement, which causes
the function to return a value to its caller, and
also specifies the value which the function
returns to its caller.
80
Explaining the function
The return statement can return the
value of any expression, so we do not
really need the local retval variable; the
function could be altered to
int multbytwo(int x)
{
return 2*x;
}

81
Calling the function
How do we call a function?
 We have been doing so informally since
day one, but now we have a chance to
call one that we have written, in full
detail.
 Here is a tiny skeletal program to call
multby2:

82
Calling the function
#include <iostream>
using namespace std;
int multbytwo(int); // function prototype
int main()
{
int i, j;
i = 3;
j = multbytwo(i);
cout << j << endl;
return 0;
}
83
Explaining the call





This looks much like our other test programs,
with the exception of the new line
int multbytwo(int);
This is a function prototype declaration.
It is an external declaration, in that it declares
something which is defined somewhere else.
We have already seen the defining instance of
the function multbytwo, but maybe the
compiler has not seen it yet.
84
Explaining the call

The function prototype declaration
contains the three pieces of information
about the function that a caller needs to
know: the

function's name,
 return type,
 argument type(s).
85
Explanation


Since we do not care what name the
multbytwo function will use to refer to its first
argument, we do not need to mention it.
On the other hand, if a function takes several
arguments, giving them names in the
prototype may make it easier to remember
which is which, so names may optionally be
used in function prototype declarations.
86
Function prototypes


The presence of the function prototype
declaration lets the compiler know that we
intend to call this function, multbytwo.
The information in the prototype lets the
compiler generate the correct code for calling
the function, and also enables the compiler to
check up on our code (by making sure, for
example, that we pass the correct number of
arguments to each function we call).
87
Function prototypes

In the body of main, the action of the
function call should be obvious: the line
j = multbytwo(i);
calls multbytwo, passing it the value of i
as its argument.
88
Calling the function


When multbytwo returns, the return value is
assigned to the variable j.
Notice that the value of main's local variable i
will become the value of multbytwo's
parameter x; this is absolutely not a problem,
and is a normal sort of affair.
89
Calling the function
This example is written out in ”longhand,” to
make each step equivalent.
 The variable i is not really needed, since we
could just as well call
j = multbytwo(3);
And the variable j is not really needed, either,
since we could just as well call

cout << multbytwo(3);

90
More on this function




Here, the call to multbytwo is a subexpression which
serves as the argument to cout.
The value returned by multbytwo is passed
immediately to cout.
Here, as in general, we see the flexibility and
generality of expressions in C++.
An argument passed to a function may be an
arbitrarily complex subexpression, and a function call
is itself an expression which may be embedded as a
subexpression within arbitrarily complicated
surrounding expressions.
91
More on this function
We should say a little more about the
mechanism by which an argument is
passed down from a caller into a
function.
 Formally, C++ is call by value, which
means that a function receives copies of
the values of its arguments

92
Passing parameters
We can illustrate this with an example.
 Suppose, in our implementation of multbytwo,
we had eliminated the unnecessary retval
variable like this:
int multbytwo(int x)
{
x = 2*x;
return x;
}

93
Passing parameters




We might wonder, if we wrote it this way, what
would happen to the value of the variable i
when we called the function
j = multbytwo(i);
When our implementation of multbytwo
changes the value of x, does that change the
value of i up in the caller?
The answer is no. x receives a copy of i's
value, so when we change x we do not
change i.
94
Passing parameters
However, there is an exception to this
rule.
 When the argument you pass to a
function is not a single variable, but is
rather an array, the function does not
receive a copy of the array, and it
therefore can modify the array in the
caller.

95
Passing parameters


The reason is that it might be too expensive to
copy the entire array, and furthermore, it can
be useful for the function to write into the
caller's array, as a way of handing back more
data than would fit in the function's single
return value.
We will see an example of an array argument
(which the function deliberately writes into) in
future lectures.
96
4.2 Function Prototypes


In modern C++ programming, it is considered
good practice to use prototype declarations
for all functions that you call.
As we mentioned, these prototypes help to
ensure that the compiler can generate correct
code for calling the functions, as well as
allowing the compiler to catch certain
mistakes you might make.
97
4.2 Function Prototypes



Strictly speaking, however, prototypes are
optional.
If you call a function for which the compiler
has not seen a prototype, the compiler will do
the best it can, assuming that you are calling
the function correctly.
If prototypes are a good idea, and if we are
going to get in the habit of writing function
prototype declarations for functions we call
that we have written.
98
Function prototypes




Such as multbytwo, what happens for library functions
such as cout? Where are their prototypes? The
answer is in the line
#include <iostream>
We have been including at the top of all of our
programs iostream is conceptually a file full of
external declarations and other information pertaining
to the ``Standard I/O'' library functions, including cout.
The #include directive (which we have been using)
arranges that all of the declarations within iostream
are considered by the compiler, rather as if we had
typed them all in ourselves
99
4.3 Function Philosophy




What makes a good function?
The most important aspect of a good
``building block'' is that have a single, welldefined task to perform.
When you find that a program is hard to
manage, it is often because it has not been
designed and broken up into functions
“cleanly”.
Two obvious reasons for moving code down
into a function are because:
100
4.3 Function Philosophy


1. It appeared in the main program several
times, such that by making it a function, it can
be written just once, and the several places
where it used to appear can be replaced with
calls to the new function.
2. The main program was getting too big, so it
could be made (presumably) smaller and
more manageable by lopping part of it off and
making it a function.
101
Functions





These two reasons are important, and they represent
significant benefits of well-chosen functions, but they
are not sufficient to automatically identify a good
function. As we have been suggesting, a good
function has at least these two additional attributes:
3. It does just one well-defined task, and does it well.
4. Its interface to the rest of the program is clean and
narrow.
Attribute 3 is just a restatement of two things we said
above.
Attribute 4 says that you should not have to keep
track of too many things when calling a function.
102
Functions


If you know what a function is supposed to do, and if
its task is simple and well-defined, there should be
just a few pieces of information you have to give it to
act upon, and one or just a few pieces of information
which it returns to you when it is done.
If you find yourself having to pass lots and lots of
information to a function, or remember details of its
internal implementation to make sure that it will work
properly this time, it is often a sign that the function is
not sufficiently well-defined.
103
functions


A poorly-defined function may be an arbitrary chunk
of code that was ripped out of a main program that
was getting too big, such that it essentially has to
have access to all of that main function's local
variables.
The whole point of breaking a program up into
functions is so that you do not have to think about the
entire program at once; ideally, you can think about
just one function at a time.
104
Functions
We say that a good function is a ``black
box,'' which is supposed to suggest that
the ``container'' it is in is opaque--callers
can not see inside it (and the function
inside can not see out).
 When you call a function, you only have
to know what it does, not how it does it.

105
Functions


When you are writing a function, you only
have to know what it is supposed to do, and
you do not have to know why or under what
circumstances its caller will be calling it.
When designing a function, we should
perhaps think about the callers just enough to
ensure that the function we are designing will
be easy to call, and that we are not
accidentally setting things up so that callers
will have to think about any internal details.
106
Functions



Some functions may be hard to write (if they have a
hard job to do, or if it is hard to make them do it truly
well), but that difficulty should be compartmentalized
along with the function itself.
Once you have written a ``hard'' function, you should
be able to sit back and relax and watch it do that hard
work on call from the rest of your program.
It should be pleasant to notice (in the ideal case) how
much easier the rest of the program is to write, now
that the hard work can be deferred to this workhorse
function.
107
Functions


In fact, if a difficult-to-write function's interface
is well-defined, you may be able to get away
with writing a quick-and-dirty version of the
function first, so that you can begin testing the
rest of the program, and then go back later
and rewrite the function to do the hard parts.
As long as the function's original interface
anticipated the hard parts, you will not have to
rewrite the rest of the program when you fix
the function.
108
Functions



What I have been trying to say in the preceding few
paragraphs is that functions are important for far more
important reasons than just saving typing.
Sometimes, we will write a function which we only call
once, just because breaking it out into a function
makes things clearer and easier.
If you find that difficulties pervade a program, that the
hard parts can not be buried inside black-box
functions and then forgotten about; if you find that
there are hard parts which involve complicated
interactions among multiple functions, then the
program probably needs redesigning.
109
Functions



For the purposes of explanation, we have been
seeming to talk so far only about ``main programs''
and the functions they call and the rationale behind
moving some piece of code down out of a ``main
program'' into a function.
But in reality, there is obviously no need to restrict
ourselves to a two-tier scheme.
Any function we find ourselves writing will often be
appropriately written in terms of sub-functions, subsub-functions, etc. (Furthermore, the ``main program,''
main(), is itself just a function.)
110
More on functions




It performs some well-defined task, which
will be useful to other parts of the program.
It might be useful to other programs as well;
that is, we might be able to reuse it (and
without having to rewrite it).
The rest of the program does not have to
know the details of how the function is
implemented.
This can make the rest of the program
easier to think about.
111
More on functions


The function performs its task well. It may be
written to do a little more than is required by
the first program that calls it, with the
anticipation that the calling program (or some
other program) may later need the extra
functionality or improved performance.
It is important that a finished function do its
job well, otherwise there might be a
reluctance to call it, and it therefore might not
achieve the goal of reusability.
112