Functions
Functions
Fundamentals of Programming II
Chapter One
Functions
A function is 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.
Functions come in two varieties: user-defined and built-in. Built-in functions are part
of compiler package--they are supplied by the manufacturer for use. In this chapter
we will discuss about user-defined functions.
Using functions in program requires that you first declare the function and 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.
The function prototype and the function definition must agree exactly about the
return type, the name, and the parameter list.
long Area(int, int); //Declaring Function Area, with two integer parameters
-1-
Assosa University
Department of Computer Science
#include <iostream.h>
unsigned short FindArea(unsigned length, unsigned width); //function
prototype
int main()
{
unsigned short length;
unsigned short width;
unsigned short area;
area= FindArea(length,width);
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. Function Definition Syntax
A function prototype tells the compiler the return type, name, and parameter list.
Every function has a return type. If one is not explicitly designated, the return type
will be int. Be sure to give every function an explicit return type. If a function does not
return a value, its return type will be void.
-2-
Assosa University
Department of Computer Science
Example 2. void PrintMessage(int whichMsg)
{
if (whichMsg == 0)
cout << "Hello.\n";
if (whichMsg == 1)
cout << "Goodbye.\n";
if (whichMsg > 1)
cout << "I'm confused.\n";
}
Local variables exist only locally within the function itself. When the function returns,
the local variables are no longer available. Variables declared within the function are
said to have "local scope." That means that they are visible and usable only within the
function in which they are defined. The scope of the variable is the block in which it is
defined.
#include <iostream.h>
float Convert(float);
int main()
{
float TempFer;
float TempCel;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> TempFer;
TempCel = Convert(TempFer);
cout << "\nHere's the temperature in Celsius: ";
cout << TempCel << endl;
return 0;
}
float Convert(float TFer)
{
float TCel;
TCel = ((TFer - 32) * 5) / 9;
return TCel;
}
Variables declared within the header of a for loop (for int i = 0; i<SomeValue; i++)
are scoped to the block in which the for loop is created.
Variables defined outside of any function have global scope and thus are available
from any function in the program.
#include <iostream.h>
void myFunction(); // prototype
-3-
Assosa University
Department of Computer Science
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n\n";
myFunction();
cout << "Back from myFunction!\n\n";
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "\n";
cout << "y from myFunction: " << y << "\n\n";
}
Function arguments do not have to all be of the same type. It is perfectly reasonable
to write a function that takes an integer, two longs, and a character as its arguments.
Assigning each step to its own intermediate variable:
The arguments passed in to the function are local to the function. Changes made to
the arguments do not affect the values in the calling function. This is known as
passing by value, which means a local copy of each argument is made in the function.
#include <iostream.h>
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
return 0;
}
-4-
Assosa University
Department of Computer Science
void swap (int x, int y)
{
int temp;
cout << "Swap. Before swap, x: " << x << " y: " <<y<< "\n";
temp = x;
x = y;
y = temp;
cout << "Swap. After swap, x: " << x << " y: " << y << "\n";
In C++, passing by reference is accomplished in two ways: using pointers and using
references. The syntax is different, but the net effect is the same. Rather than a copy
being created within the scope of the function, the actual original object is passed into
the function. Passing an object by reference allows the function to change the object
being referred to.
#include <iostream.h>
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " <<y<< "\n";
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " <<y << "\n";
return 0;
}
void swap (int &rx, int &ry)
{
int temp;s
cout << "Swap. Before swap, rx: " <<rx<< " ry: " <<ry<<"\n";
temp = rx;
rx = ry;
ry = temp;
cout << "Swap. After swap, rx: " <<rx<< " ry: " <<ry<< "\n";
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
-5-
Assosa University
Department of Computer Science
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());
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. Thus,
if you have a function declared as
long myFunction(int);
the function must in fact take an integer variable. A default value is a value to use if
none is supplied. The preceding declaration could be rewritten as
This prototype says, "myFunction() returns a long and takes an integer parameter. If
an argument is not supplied, use the default value of 50." Because parameter names
are not required in function prototypes, this declaration could have been written as
The function definition is not changed by declaring a default parameter. The function
definition header for this function would be
If the calling function did not include a parameter, the compiler would fill x with the
default value of 50. The name of the default parameter in the prototype need not be
the same as the name in the function header; the default value is assigned by position,
not name. Any or all of the function's parameters can be assigned default values. The
one restriction is this: If any of the parameters does not have a default value, no
previous parameter may have a default value.
If the function prototype looks like
you can assign a default value to Param2 only if you have assigned a default value to
Param3. You can assign a default value to Param1 only if you've assigned default
values to both Param2 and Param3. Listing 5.7 demonstrates the use of default
values.
A demonstration of default parameter values.
#include <iostream.h>
int main()
{
int length = 100;
int width = 50;
int height = 2;
-6-
Assosa University
Department of Computer Science
int area;
area = AreaCube(length);
cout << "Third time area equals: " << area << "\n";
return 0;
}
When you call the function, execution of the program jumps to those instructions, and
when the function returns, execution jumps back to the next line in the calling
function.. It turns out that some functions are very small, just a line or two of code,
and some efficiency can be gained if the program can avoid making these jumps just
to execute one or two instructions. When programmers speak of efficiency, they
usually mean speed: the program runs faster if the function call can be avoided.
If a function is declared with the keyword inline, compiler copies the code from the
inline function directly into the calling function.
Syntax
#include <iostream.h>
int main()
{
int target;
cout << "Enter a number to work with: ";
cin >> target;
cout << "\n";
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
return 0;
}
-7-
Assosa University
Department of Computer Science
5.8. Recursive Functions
Most mathematical functions that we are familiar with are described by a simple
formula. For example, we can convert temperatures from Fahrenheit to Celsius by
applying the formula
C = 5 (F-32) / 9
Given this formula, it is trivial to write a C++ function; with declarations and braces
removed, the one line formula above translates into one line C++ statement.
Mathematical functions are sometimes defined in a less standard form. For example
we can define a function f, valid on non negative integers, that satisfies:
f(0) = 0
f(x) = 2, f(x-1) +x2 for x>0, x Z
From this definition,
f(3) = 2f(2) + 32
= 2f(2) + 9 now we should compute f(2) first.
f(2) = 2f(1) + 22
= 2f(1) + 4 now we should compute f(1) first.
f(1) = 2f(0) + 12
= 2f(0) + 1 now we should compute f(0) first.
f(0) = 0
f(1) = 2 (0) + 1
=0+1 =1
f(2) = 2 (1) + 4
=2+4 =6
=> f(3) = 2 (6) + 9
= 12 + 9 = 21
A function that is defined in terms of it self is called recursive. f(0) in the above
function is the value which is the function directly known with out resorting to
recursion. Such case is known as the base case. A recursive function without a base
case is meaningless. When writing recursive routines, it is crucial to keep in mind the
four basic rules of recursion. These are:
1. Base case: you must always have some Base case, which can be solved with
out recursion.
2. Making progress: for the cases that are to be solved recursively, the
recursive call must always be to a case that makes progress to ward a base
case.
3. Design rule: Assume that all recursive calls work without fail. In order to find
f(n) recursively you can assume f(n-k) will work (k 1)
4. Compound interest rule: never duplicate work by solving the same instance
of a problem in separate recursive rule.
Some examples of recursive problems
a) The factorial function f(n) = n!
f(n) can be defined as:
f(N) = N x (N-1) x (N-2) x (N-3) x ……..x 1 this is iterative defn
b) Fibonacci progress :
-8-
Assosa University
Department of Computer Science
is a sequence in which the ith term equals f(i) defined as
-9-