SlideShare a Scribd company logo
1
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.
2
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
3
Display a menu
Simple Menus
1. Program displays a menu of choices
2. User enters a choice
3. Program responds to choice
4. Go back to to 1
4
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main( ) {
return 0;
}
function prototype consisting of
<type> function name (types of parameters);
So void here means no return type or parameters
expected. It is not required to use void here.
5
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int 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 : “;
}
Definition:
like a mini program
or sub program
6
Display a menu
Simple DisplayMenu() function
#include <iostream>
void DisplayMenu(void);
int main() {
int response;
DisplayMenu();
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 : “;
}
Function call
from within
main()
Prompt
7
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
8
Display a menu and Get response
#include <iostream>
void DisplayMenu(void);
int main() {
int 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 : “;
}
Get response
9
Process the response
by using the switch statement
10
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
The switch Statement
Syntax
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
case valueN: statementN;
break;
default: statement;
}
expression must return an integer value, i.e. be an integer
The switch Statement
with char expression
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;
}
//next statement
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 << “The greatest ” << endl;
case 2: cout << “Exciting team ”<< endl;
case 3: cout << “Boring ” << endl;
case 4: cout << “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:
20
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 << “The greatest“ << endl;
case 2: cout << “Exciting team“ << endl;
case 3: cout << “Boring“ << endl;
case 4: cout << “Bye Bye << endl;
};
return 0;
}
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 : ";
}
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;
}
22
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
23
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 ‘:’
24
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.
25
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
26
Types of loops
while
for
do..while
27
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.
– Data entry from users
28
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.
29
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’ ) ) ;
}
Function Using Do-While
29
30
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.
31
Do-While Loop
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.
Statement
Expression
DO
WHILE
FALSE
TRUE
The for Statement Syntax
Example:
for (count=1; count < 7; count++)
{
cout << count << endl;
}
//next C++ statements;
start condition change expression
while condition
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
int num;
cout << "NUMBERtSQUAREtCUBEn“;
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
A Simple Example
Create a table with a for loop
NUMBER SQUARE CUBE
---------- ---------- ------
1 1 1
2 4 8
. . .
. . .
10 100 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).
 e.g. if number = 12, divisors are 1,2,3,4,6,12
Think I can
use % operator
to find divisors
37
Solution Design
1. Get the number from user
2. By starting with check number=1 and
finish with number (is this efficient?)
1. 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
38
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
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++);
Common errors in constructing
for Statements
40
Infinite loops example 1
for (j=0; j>=0; j++) {
cout << j << endl;
}
What will happen here?
//see infiniteloop1.cpp
41
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?
42
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!
43
Example of Repetition
int n;
for ( int i = 1 ; i <= n ; i++ )
{
cout << i << “ Potato” << endl;
}
//see usefor1.cpp
// useofFunction5.cpp uses an array as a
global variable
44
Example of Repetition
num
int n;
for ( int i = 1 ; i <= n ; i++ )
cout << i << “ Potato” << endl;
OUTPUT
?
45
Example of Repetition
num
OUTPUT
1
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
46
Example of Repetition
num
OUTPUT
1
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
true
47
Example of Repetition
num
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
1
1Potato
48
Example of Repetition
num
OUTPUT
2
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
1Potato
49
Example of Repetition
num
OUTPUT
2
true
1Potato
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
50
Example of Repetition
num
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
2
1Potato
2Potato
51
Example of Repetition
num
OUTPUT
3
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
1Potato
2Potato
52
Example of Repetition
num
OUTPUT
3
true
1Potato
2Potato
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
53
Example of Repetition
num
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
OUTPUT
3
1Potato
2Potato
3Potato
54
Example of Repetition
num
OUTPUT
4
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
1Potato
2Potato
3Potato
55
Example of Repetition
num
OUTPUT
4
false
1Potato
2Potato
3Potato
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
56
Example of Repetition
num
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.
4
false
int num;
for ( num = 1 ; num <= 3 ; num++ )
cout << num << “Potato” << endl;
57
The output was:
1Potato
2Potato
3Potato
Nested Loops
Recall when a control structure is contained
within another control structure, the inner one
is said to be nested.
for ...
if ...
for ...
for...
You may have repetition within decision and
vice versa.
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
}
Nested Loops - Ex.1
for within for
60
CAUTION!
What is the output from this
loop?
int count;
for (count = 0; count < 10; count++) ;
{
cout << “*” ;
}
//see useforloop2.cpp
61
 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
Infinite loop example 2
OUTPUT
*
Output
0 1 2 3 **
1 1 2 3 **
2 1 2 3 **
3 1 2 3 **
4 1 2 3 **
Nested Loops – Example 1
variable row changes from
0 to 4
variable col changes from
1 to 3 for every time row
changes
63
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
64
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
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;
68
Break and Continue
 Now see UseContinue1.cpp
69
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:
70
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.
71
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.
72
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.
73
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.
74
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.
75
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).
76
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.
77
A simple function
int multbytwo(int x)
{
int retval; //a local variable
retval = 2*x;
return retval;
}
78
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.
79
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.
80
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.
81
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;
}
82
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:
83
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;
}
84
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.
85
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).
86
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.
87
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).
88
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.
89
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.
90
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);
91
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.
92
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
93
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;
}
94
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.
95
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.
96
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.
97
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.
98
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.
99
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
100
4.3 Function Philosophy
 What makes a good function?
 The most important aspect of a good
``building block'' is that have a single, well-
defined 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:
101
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.
102
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.
103
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.
104
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.
105
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.
106
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.
107
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.
108
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.
109
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.
110
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, sub-
sub-functions, etc. (Furthermore, the ``main program,''
main(), is itself just a function.)
111
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.
112
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.

More Related Content

Similar to Loops_and_FunctionsWeek4_0.ppt

Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
SURBHI SAROHA
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
sanjay
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Krishna Raj
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
Jlien Ching
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
Jlien Ching
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
SHRIRANG PINJARKAR
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
Farooq Mian
 
Lesson 2 starting output
Lesson 2 starting outputLesson 2 starting output
Lesson 2 starting output
WayneJones104
 
Loops
LoopsLoops
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
Vladislav Hadzhiyski
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
Munazza-Mah-Jabeen
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 

Similar to Loops_and_FunctionsWeek4_0.ppt (20)

Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Iteration
IterationIteration
Iteration
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Lesson 2 starting output
Lesson 2 starting outputLesson 2 starting output
Lesson 2 starting output
 
Loops
LoopsLoops
Loops
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 

More from KamranAli649587

UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdfUNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
KamranAli649587
 
Data design and analysis of computing tools
Data design and analysis of computing toolsData design and analysis of computing tools
Data design and analysis of computing tools
KamranAli649587
 
graphs data structure and algorithm link list
graphs data structure and algorithm link listgraphs data structure and algorithm link list
graphs data structure and algorithm link list
KamranAli649587
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
KamranAli649587
 
Encoder-and-decoder.pptx
Encoder-and-decoder.pptxEncoder-and-decoder.pptx
Encoder-and-decoder.pptx
KamranAli649587
 
Radio propagation model...pptx
Radio propagation model...pptxRadio propagation model...pptx
Radio propagation model...pptx
KamranAli649587
 
Lecture+06-TypesVars.ppt
Lecture+06-TypesVars.pptLecture+06-TypesVars.ppt
Lecture+06-TypesVars.ppt
KamranAli649587
 
C++InputOutput.PPT
C++InputOutput.PPTC++InputOutput.PPT
C++InputOutput.PPT
KamranAli649587
 
radiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdfradiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdf
KamranAli649587
 
cluster.pptx
cluster.pptxcluster.pptx
cluster.pptx
KamranAli649587
 
Week11-EvaluationMethods.ppt
Week11-EvaluationMethods.pptWeek11-EvaluationMethods.ppt
Week11-EvaluationMethods.ppt
KamranAli649587
 
Week6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.pptWeek6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.ppt
KamranAli649587
 
null-13.pdf
null-13.pdfnull-13.pdf
null-13.pdf
KamranAli649587
 
Reaches
ReachesReaches
null-6.pdf
null-6.pdfnull-6.pdf
null-6.pdf
KamranAli649587
 
null-1.pptx
null-1.pptxnull-1.pptx
null-1.pptx
KamranAli649587
 
Lect-01.ppt
Lect-01.pptLect-01.ppt
Lect-01.ppt
KamranAli649587
 
Db_05.ppt
Db_05.pptDb_05.ppt
Db_05.ppt
KamranAli649587
 
ch7.ppt
ch7.pptch7.ppt
lect09.ppt
lect09.pptlect09.ppt
lect09.ppt
KamranAli649587
 

More from KamranAli649587 (20)

UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdfUNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
 
Data design and analysis of computing tools
Data design and analysis of computing toolsData design and analysis of computing tools
Data design and analysis of computing tools
 
graphs data structure and algorithm link list
graphs data structure and algorithm link listgraphs data structure and algorithm link list
graphs data structure and algorithm link list
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
Encoder-and-decoder.pptx
Encoder-and-decoder.pptxEncoder-and-decoder.pptx
Encoder-and-decoder.pptx
 
Radio propagation model...pptx
Radio propagation model...pptxRadio propagation model...pptx
Radio propagation model...pptx
 
Lecture+06-TypesVars.ppt
Lecture+06-TypesVars.pptLecture+06-TypesVars.ppt
Lecture+06-TypesVars.ppt
 
C++InputOutput.PPT
C++InputOutput.PPTC++InputOutput.PPT
C++InputOutput.PPT
 
radiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdfradiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdf
 
cluster.pptx
cluster.pptxcluster.pptx
cluster.pptx
 
Week11-EvaluationMethods.ppt
Week11-EvaluationMethods.pptWeek11-EvaluationMethods.ppt
Week11-EvaluationMethods.ppt
 
Week6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.pptWeek6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.ppt
 
null-13.pdf
null-13.pdfnull-13.pdf
null-13.pdf
 
Reaches
ReachesReaches
Reaches
 
null-6.pdf
null-6.pdfnull-6.pdf
null-6.pdf
 
null-1.pptx
null-1.pptxnull-1.pptx
null-1.pptx
 
Lect-01.ppt
Lect-01.pptLect-01.ppt
Lect-01.ppt
 
Db_05.ppt
Db_05.pptDb_05.ppt
Db_05.ppt
 
ch7.ppt
ch7.pptch7.ppt
ch7.ppt
 
lect09.ppt
lect09.pptlect09.ppt
lect09.ppt
 

Recently uploaded

一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
vcaxypu
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
jerlynmaetalle
 
FP Growth Algorithm and its Applications
FP Growth Algorithm and its ApplicationsFP Growth Algorithm and its Applications
FP Growth Algorithm and its Applications
MaleehaSheikh2
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Subhajit Sahu
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
NABLAS株式会社
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
slg6lamcq
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
benishzehra469
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
John Andrews
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
nscud
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
ahzuo
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单
ocavb
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
NABLAS株式会社
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
oz8q3jxlp
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
pchutichetpong
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
enxupq
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
u86oixdj
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
mbawufebxi
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
AbhimanyuSinha9
 

Recently uploaded (20)

一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
 
FP Growth Algorithm and its Applications
FP Growth Algorithm and its ApplicationsFP Growth Algorithm and its Applications
FP Growth Algorithm and its Applications
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
 

Loops_and_FunctionsWeek4_0.ppt

  • 1. 1 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.
  • 2. 2 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
  • 3. 3 Display a menu Simple Menus 1. Program displays a menu of choices 2. User enters a choice 3. Program responds to choice 4. Go back to to 1
  • 4. 4 Display a menu Simple DisplayMenu() function #include <iostream> void DisplayMenu(void); int main( ) { return 0; } function prototype consisting of <type> function name (types of parameters); So void here means no return type or parameters expected. It is not required to use void here.
  • 5. 5 Display a menu Simple DisplayMenu() function #include <iostream> void DisplayMenu(void); int 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 : “; } Definition: like a mini program or sub program
  • 6. 6 Display a menu Simple DisplayMenu() function #include <iostream> void DisplayMenu(void); int main() { int response; DisplayMenu(); 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 : “; } Function call from within main() Prompt
  • 7. 7 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
  • 8. 8 Display a menu and Get response #include <iostream> void DisplayMenu(void); int main() { int 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 : “; } Get response
  • 9. 9 Process the response by using the switch statement
  • 10. 10 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
  • 11. The switch Statement Syntax switch (expression) { case value1: statement1; break; case value2: statement2; break; case valueN: statementN; break; default: statement; } expression must return an integer value, i.e. be an integer
  • 12. The switch Statement with char expression 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; } //next statement
  • 13. 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.
  • 14. The switch Statement illustrate fall through again switch (choice){ case 1: cout << “The greatest ” << endl; case 2: cout << “Exciting team ”<< endl; case 3: cout << “Boring ” << endl; case 4: cout << “Bye Bye << endl; }
  • 15. The switch Statement What will be the output when the user enters 1? The greatest Exciting team Boring Bye Bye
  • 16. The switch Statement What will be the output when the user enters 2? Exciting team Boring Bye Bye
  • 17. The switch Statement What will be the output when the user enters 3? Boring Bye Bye
  • 18. The switch Statement What will be the output when the user enters 4? Bye Bye
  • 19. 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:
  • 20. 20 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 << “The greatest“ << endl; case 2: cout << “Exciting team“ << endl; case 3: cout << “Boring“ << endl; case 4: cout << “Bye Bye << endl; }; return 0; } 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 : "; }
  • 21. 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; }
  • 22. 22 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
  • 23. 23 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 ‘:’
  • 24. 24 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.
  • 25. 25 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
  • 27. 27 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. – Data entry from users
  • 28. 28 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.
  • 29. 29 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’ ) ) ; } Function Using Do-While 29
  • 30. 30 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.
  • 31. 31 Do-While Loop 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. Statement Expression DO WHILE FALSE TRUE
  • 32. The for Statement Syntax Example: for (count=1; count < 7; count++) { cout << count << endl; } //next C++ statements; start condition change expression while condition
  • 33. 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
  • 34. int num; cout << "NUMBERtSQUAREtCUBEn“; 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 A Simple Example Create a table with a for loop NUMBER SQUARE CUBE ---------- ---------- ------ 1 1 1 2 4 8 . . . . . . 10 100 1000
  • 35. Use of the for loop  Please see the following files  Harmonic.cpp  BaselSeries.cpp These are two very important series in mathematics. 35
  • 36. 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).  e.g. if number = 12, divisors are 1,2,3,4,6,12 Think I can use % operator to find divisors
  • 37. 37 Solution Design 1. Get the number from user 2. By starting with check number=1 and finish with number (is this efficient?) 1. 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
  • 38. 38 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
  • 39. 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++); Common errors in constructing for Statements
  • 40. 40 Infinite loops example 1 for (j=0; j>=0; j++) { cout << j << endl; } What will happen here? //see infiniteloop1.cpp
  • 41. 41 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?
  • 42. 42 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!
  • 43. 43 Example of Repetition int n; for ( int i = 1 ; i <= n ; i++ ) { cout << i << “ Potato” << endl; } //see usefor1.cpp // useofFunction5.cpp uses an array as a global variable
  • 44. 44 Example of Repetition num int n; for ( int i = 1 ; i <= n ; i++ ) cout << i << “ Potato” << endl; OUTPUT ?
  • 45. 45 Example of Repetition num OUTPUT 1 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;
  • 46. 46 Example of Repetition num OUTPUT 1 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; true
  • 47. 47 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 1 1Potato
  • 48. 48 Example of Repetition num OUTPUT 2 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato
  • 49. 49 Example of Repetition num OUTPUT 2 true 1Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;
  • 50. 50 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 2 1Potato 2Potato
  • 51. 51 Example of Repetition num OUTPUT 3 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato 2Potato
  • 52. 52 Example of Repetition num OUTPUT 3 true 1Potato 2Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;
  • 53. 53 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 3 1Potato 2Potato 3Potato
  • 54. 54 Example of Repetition num OUTPUT 4 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato 2Potato 3Potato
  • 55. 55 Example of Repetition num OUTPUT 4 false 1Potato 2Potato 3Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;
  • 56. 56 Example of Repetition num 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. 4 false int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;
  • 58. Nested Loops Recall when a control structure is contained within another control structure, the inner one is said to be nested. for ... if ... for ... for... You may have repetition within decision and vice versa.
  • 59. 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 } Nested Loops - Ex.1 for within for
  • 60. 60 CAUTION! What is the output from this loop? int count; for (count = 0; count < 10; count++) ; { cout << “*” ; } //see useforloop2.cpp
  • 61. 61  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 Infinite loop example 2 OUTPUT *
  • 62. Output 0 1 2 3 ** 1 1 2 3 ** 2 1 2 3 ** 3 1 2 3 ** 4 1 2 3 ** Nested Loops – Example 1 variable row changes from 0 to 4 variable col changes from 1 to 3 for every time row changes
  • 63. 63 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
  • 64. 64 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
  • 65. 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.
  • 66. 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.
  • 67. break and continue while ( - - - ) { statement 1; if( - - - ) continue statement 2; } statement 3; while ( - - - ) { statement 1; if( - - - ) break statement 2; } statement 3;
  • 68. 68 Break and Continue  Now see UseContinue1.cpp
  • 69. 69 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:
  • 70. 70 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.
  • 71. 71 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.
  • 72. 72 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.
  • 73. 73 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.
  • 74. 74 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.
  • 75. 75 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).
  • 76. 76 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.
  • 77. 77 A simple function int multbytwo(int x) { int retval; //a local variable retval = 2*x; return retval; }
  • 78. 78 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.
  • 79. 79 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.
  • 80. 80 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.
  • 81. 81 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; }
  • 82. 82 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:
  • 83. 83 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; }
  • 84. 84 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.
  • 85. 85 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).
  • 86. 86 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.
  • 87. 87 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).
  • 88. 88 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.
  • 89. 89 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.
  • 90. 90 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);
  • 91. 91 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.
  • 92. 92 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
  • 93. 93 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; }
  • 94. 94 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.
  • 95. 95 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.
  • 96. 96 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.
  • 97. 97 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.
  • 98. 98 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.
  • 99. 99 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
  • 100. 100 4.3 Function Philosophy  What makes a good function?  The most important aspect of a good ``building block'' is that have a single, well- defined 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:
  • 101. 101 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.
  • 102. 102 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.
  • 103. 103 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.
  • 104. 104 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.
  • 105. 105 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.
  • 106. 106 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.
  • 107. 107 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.
  • 108. 108 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.
  • 109. 109 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.
  • 110. 110 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, sub- sub-functions, etc. (Furthermore, the ``main program,'' main(), is itself just a function.)
  • 111. 111 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.
  • 112. 112 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.