0% found this document useful (0 votes)
9 views

COMP 103 L6-Functions - Stud.

Programming

Uploaded by

comfortrosey831
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

COMP 103 L6-Functions - Stud.

Programming

Uploaded by

comfortrosey831
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

COMP 103 Introduction to

Programming

FUNCTIONS

Charles Fomevor
CHECKLIST
1.HOW MANY PROGRAMS HAVE YOU WRITTEN
TO DATE?
2.HOW MANY PROGRAMS HAVE YOU COMPILED
TO DATE?
3.HOW MANY PROGRAMS HAVE YOU
DEBUGGED TO DATE?
4.HOW MANY PROGRAMS HAVE YOU GOT
WORKING CORRECTLY TO DATE?
5.GET HELP BUT DO IT YOURSELF MORE
Functions
• Although object-oriented programming has
shifted attention from functions and toward
objects, functions nonetheless remain a central
component of any program.
• We look at the following:
– What a function is and what its parts are.
– How to declare and define functions.
– How to pass parameters into functions.
– How to return a value from a function.
What Is a Function?
• A function is, in effect, a subprogram that can
act on data and return a value.
• Every C++ program has at least one function,
main(). When your program starts, main() is
called automatically.
• main() might call other functions, some of
which might call still others.
What Is a Function? (continued)
Each function has its own name, and when that
name is encountered, the execution of the
program branches to the body of that function.
When the function returns, execution resumes on
the next line of the calling function.

When a program calls a function, execution


switches to the function and then resumes at the
line after the function call
What Is a Function? (continued)
• Well-designed functions perform a specific and
easily understood task.
• Complicated tasks should be broken down into
multiple functions, and then each can be called
in turn.
• Functions come in two varieties: user-defined
and built-in. Built-in functions are part of your
compiler
• package--they are supplied by the
manufacturer for your use.
Declaring and Defining Functions
• Using functions in your program requires that
you first declare the function and that you then
define the function.
• The declaration tells the compiler the name,
return type, and parameters of the function.
• The definition tells the compiler how the
function works.
• No function can be called from any other
function that hasn't first been declared.
• The declaration of a function is called its
prototype.
Declaring the Function
• There are three ways to declare a function:
• Write your prototype into a file, and then use
the #include directive to include it in your
program.
• Write the prototype into the file in which your
function is used.
• Define the function before it is called by any
other function. When you do this, the
definition acts as its own declaration.
Function declaration:Using defining
• Although you can define the function before
using it, and thus avoid the necessity of
creating a function prototype, this is not good
programming practice for three reasons.
• 1. it is a bad idea to require that functions
appear in a file in a particular order. Doing so
makes it hard to maintain the program as
requirements change.

● 2. Function declaration:Using defining
● it is possible that function A() needs to be able to call
function B(), but the reverse is also true under some
circumstances.
● It is not possible to define function A() before you define
function B() and also to define function B() before you define
function A(), so at least one of them must be declared in any
Using defining to declare a
function
• 3. function prototypes are a good and powerful
debugging technique.
• If your prototype declares that your function
takes a particular set of parameters, or that it
returns a particular type of value, and then
your function does not match the prototype,
the compiler can flag your error instead of
waiting for it to show itself when you run the
program.
Function Prototypes
• Many of the built-in functions you use will have
their function prototypes already written in the
files you include in your program by using
#include.
• For functions you write yourself, you must
include the prototype.
• The function prototype is a statement, which
means it ends with a semicolon.
• It consists of the function's return type, name,
and parameter list.
Function prototype
• The function prototype and the function
definition must agree exactly about the return
type, the name, and the parameter list.
• If they do not agree, you will get a compile-
time error.
• Note, however, that the function prototype
does not need to contain the names of the
parameters, just their types.

Function prototype

A prototype that looks like this is perfectly legal:

long Area(int length, int width);

Note that all functions have a return type.


If none is explicitly stated, the return type
defaults to int.
Examples of a function

1: // Listing 5.1 - demonstrates the use of
function prototypes

2:

3: typedef unsigned short
USHORT;

4: #include <iostream.h>

5: USHORT FindArea(USHORT
length, USHORT width); //function prototype

6:

7: int main
Example
• 7: int main()
• 8: {
• 9: USHORT lengthOfYard;
• 10: USHORT widthOfYard;
• 11: USHORT areaOfYard;
• 12:
• 13: cout << "\nHow wide is your


14: cin >> widthOfYard;

15: cout << "\nHow long is your yard? ";

16: cin >> lengthOfYard;

17:

18: areaOfYard= FindArea(lengthOfYard,widthOfYard);

19:

20: cout << "\nYour yard is ";

21: cout << areaOfYard;

22: cout << " square feet\n\n";

23: return 0;

24: }

25:

26: USHORT FindArea(USHORT l, USHORT w)

27: {

28: return l * w; yard? "; 29: }

Defining the Function
• The definition of a function consists of the
function header and its body.
• The header is exactly like the function
prototype, except that the parameters must be
named, and there is no terminating semicolon.
• The body of the function is a set of statements
enclosed in braces.
• Next slide shows the header and body of a
function.
Header and body of function
• Function Prototype Syntax
return_type function_name ( [type
[parameterName]]...);

• Function Definition Syntax


return_type function_name ( [type
parameterName]...)
{
statements;
}
Header and body of function
● A function prototype tells the compiler the
return type, name, and parameter list.

● Functions are not required to have parameters


● A prototype always ends with a semicolon (;).
Examples of Function Prototype
• long FindArea(long length, long width); //
returns long, has two parameters
• void PrintMessage(int messageNumber); //
returns void, has one parameter
• int GetChoice(); // returns int, has no
parameters
• BadFunction(); // returns int, has no
parameters
Parameters

● double FindArea(double length, double width);


// returns double, has two parameters

● void PrintMessage(int messageNumber); //


returns void, has one parameter
Examples of Function Definition
• double Area(long l, long w)
• {
• return l * w;
• }

• void PrintMessage(int whichMsg)
• {
• if (whichMsg == 0)
• cout << "Hello.\n";
• if (whichMsg == 1)
• cout << "Goodbye.\n";
• if (whichMsg > 1)
• cout << "I'm confused.\n";
• }
Examples of Function Definition
● if (whichMsg == 0)
● cout << "Hello.\n";
● if (whichMsg == 1)
● cout << "Goodbye.\n";
● if (whichMsg > 1)
● cout << "I'm confused.\n";
● }
Local Variables
• Not only can you pass in variables to the
function, but you also can declare variables
within the body of the function.
• This is done using local variables, so named
because they exist only locally within the
function itself.
• When the function returns, the local variables
are no longer available.

Local Variables
● Local variables are defined like any other
variables.
● The parameters passed in to the function are
also considered local variables and can be used
exactly as if they had been defined within the
body of the function.
Local Variables
● Local variables are defined like any other
variables.
● The parameters passed in to the function are
also considered local variables and can be used
exactly as if they had been defined within the
body of the function.
Example: local variable
• 1: #include <iostream.h>
• 2:
• 3: float Convert(float);
• 4: int main()
• 5: {
• 6: float TempFer;
• 7: float TempCel;
• 8:
• 9: cout << "Please enter the temperature
in Fahrenheit: ";
• 21: return TempCel;
• 22: }
Example: local variable

● 10: cin >> TempFer;


● 11: TempCel = Convert(TempFer);
● 12: cout << "\nHere's the temperature in
Celsius: ";
● 13: cout << TempCel << endl;
● 14: return 0;
● 15: }
● 16:
● 17: float Convert(float TempFer)
● 18: {
● 19: float TempCel;
● 20: TempCel = ((TempFer - 32) * 5) / 9;
Example: local variable
● cout << "Please enter the temperature in
Fahrenheit: ";
● 10: cin >> TempFer;
● 11: TempCel = Convert(TempFer);
● 12: cout << "\nHere's the temperature
in Celsius: ";
● 13: cout << TempCel << endl;
● 14: return 0;
● 15: }
● 16:
● 17: float C
Try this example
• 1: #include <iostream.h>
• 2:
• 3: float Convert(float);
• 4: int main()
• 5: {
• 6: float TempFer;
• 7: float TempCel;
• 8:
• 9: cout << "Please enter the temperature in
Fahrenheit: ";
• 10: cin >> TempFer;
• 11: TempCel = Convert(TempFer);
• 12: cout << "\nHere's the temperature in
Celsius: ";


13: cout << TempCel << endl;

14: }

15:

16: float Convert(float Fer)

17: {

18: float Cel;

19: Cel = ((Fer - 32) * 5) / 9;

20: return Cel;

21: }
SCOPE
• A variable has scope, which determines how
long it is available to your program and where
it can be accessed.
• Variables declared within a block are scoped to
that block; they can be accessed only within
that block and "go out of existence" when that
block ends.
SCOPE

Global variables have global scope and are


available anywhere within your program.
● Normally scope is obvious, but there are some
tricky exceptions. Eg for loop.
Global Variables
• Variables defined outside of any function have
global scope and thus are available from any
function in
• the program, including main().
• Local variables with the same name as global
variables do not change the global variables.

Global Variables
● A local variable with the same name as a global
variable hides the global variable, however.
● If a function has a variable with the same name
as a global variable, the name refers to the
local variable--not the global--when used
within the function.
More on Local Variables
• Variables declared within the function are said
to have "local scope."

• That means, as discussed, that they are visible


and usable only within the function in which
they are defined.

More on Local Variables

In fact, in C++ you can define variables
anywhere within the function, not just at its
top.

The scope of the variable is the block in which
it is defined.

Thus, if you define a variable inside a set of
braces within the function, that variable is
available only within that block.
Return Values
• Functions return a value or return void. Void is
a signal to the compiler that no value will be
returned.
• To return a value from a function, write the
keyword return followed by the value you want
to return.
• The value might itself be an expression that
returns a value. For example:
return 5;
return (x > 5);
return (MyFunction());
Return Values
● These are all legal return statements, assuming
that the function MyFunction() itself returns a
value.
● The value in the second statement, return (x >
5), will be zero if x is not greater than 5, or it
will be 1. What is returned is the value of the
expression, 0 (false) or 1 (true), not the value
of x.
Default Parameters
• For every parameter you declare in a function
prototype and definition, the calling function
must pass in a value.
• The value passed in must be of the declared
type.

Default Parameters
● Thus, if you have a function declared as
● long myFunction(int);
● the function must in fact take an integer
variable.
● If the function definition differs, or if you fail
to pass in an integer, you will get a compiler
error unless you declare a default value.
Overloading Functions
• C++ enables you to create more than one
function with the same name.
• This is called function Overloading (also called
function polymorphism).
• The functions must differ in their parameter
list, with a different type of parameter, a
different number of parameters, or both. o
functions with the same name and parameter
list, but different return types, generate a
compiler error.

Here's an example:

int myFunction (int, int);

int myFunction (long, long);

int myFunction (long);

myFunction() is overloaded with three different
parameter lists.

The first and second versions differ in the types of the
parameters, and the third differs in the number of
parameters.

The return types can be the same or different on
overloaded functions.

Example
• You would like to be able to pass in an int, a
long, a float, or a double.
• Without function overloading, you would have
to create four function names:
int DoubleInt(int);
long DoubleLong(long);
float DoubleFloat(float);
double DoubleDouble(double);
Example

● With function overloading, you make this


declaration:
● int Double(int);
● long Double(long);
● float Double(float);
● double Double(double);
● You don't have to worry about which one to call;
you just pass in a variable, and the right function
is called automatically.

Recursion
• A function can call itself. This is called
recursion, and recursion can be direct or
indirect.
• It is direct when a function calls itself; it is
indirect recursion when a function calls
another function that then calls the first
function.
• Some problems are most easily solved by
recursion, usually those in which you act on
data and then act in the same way on the
result.
Recursion

● Both types of recursion, direct and indirect,


come in two varieties:
● those that eventually end and produce an answer,
and
● those that never end and produce a runtime failure.
● Programmers think that the latter is quite
funny (when it happens to someone else).
● It is important to note that when a function
calls itself, a new copy of that function is run.
Example – Fibonacci series
• To illustrate solving a problem using recursion,
consider the Fibonacci series:
• 1,1,2,3,5,8,13,21,34...
• Each number, after the second, is the sum of
the two numbers before it.
• A Fibonacci problem might be to determine
what the 12th number in the series is.

Example – Fibonacci series
● Recursive functions need a stop condition.
● Something must happen to cause the program
to stop
● recursing, or it will never end.
● In the Fibonacci series, n < 3 is a stop
condition.
A closer look at fibonacci
• The algorithm to use is this:
1. Ask the user for a position in the series.
2. Call the fib() function with that position,
passing in the value the user entered.
3. The fib() function examines the
argument (n). If n < 3 it returns 1; otherwise,
fib() calls itself (recursively) passing in n-2, calls
itself again passing in n-1, and returns the sum.

A closer look at fibonacci
● If you call fib(1), it returns 1. If you call fib(2), it
returns 1. If you call fib(3), it returns the sum
of calling fib(2) and fib(1). Because fib(2)
returns 1 and fib(1) returns 1, fib(3) will return
2.

Furthermore
• This method is not the most efficient way to
solve this problem (in fib(20) the fib() function
is called 13,529 times!), but it does work.
• Be careful: if you feed in too large a number,
you'll run out of memory.
• Every time fib() is called, memory is set aside.
• When it returns, memory is freed.
• With recursion, memory continues to be set
aside before it is freed, and this system can eat
memory very quickly.
Fibonacci Program
• Listing 5.10. Demonstrates recursion using the Fibonacci series.

• 1: // Listing 5.10 - demonstrates recursion
• 2: // Fibonacci find.
• 3: // Finds the nth Fibonacci number
• 4: // Uses this algorithm: Fib(n) = fib(n-1) + fib(n-2)
return( fib(n-2) + fib(n-1));
• 39: }
• 40: } 14: int n, answer;
• 15: cout << "Enter number to find: ";
• 16: cin >> n;
• 17:
• 18: cout << "\n\n";
• 19:
• 20: answer = fib(n);


14: int n, answer;

15: cout << "Enter number to find: ";

16: cin >> n;

17:

18: cout << "\n\n";

19:

20: answer = fib(n);

21:

22: cout << answer << " is the " << n << "th Fibonacci number\n";

23: return 0;

24: }

25:

26: int fib (int n)

27: {

28: cout << "Processing fib(" << n << ")... ";

29:

30: if (n < 3 )

31: {

32: cout << "Return 1!\n";

33: return (1);

34: }

35: else

36: {

37: cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\n";

38:

4: // Uses this algorithm: Fib(n) = fib(n-1) + fib(n-2)

5: // Stop conditions: n = 2 || n = 1

6:

7: #include <iostream.h>

8:

9: int fib(int n);

10:

11: int main()

12: {

13:

14: int n, answer;

15: cout << "Enter number to find: ";

16: cin >> n;

17:

1
CHECKLIST
• HOW MANY PROGRAMS HAVE YOU WRITTEN
TO DATE?
• HOW MANY PROGRAMS HAVE YOU COMPILED
TO DATE?
• HOW MANY PROGRAMS HAVE YOU DEBUGGED
TO DATE?
• HOW MANY PROGRAMS HAVE YOU GOT
WORKING CORRECTLY TO DATE?
• GET HELP BUT DO IT YOURSELF MORE
Next Week


You might also like