1. ï Introduction
ï Function Definition
ï Void function
ï Global Vs Local variables
ï Random Number Generator
ï Recursion
ï Function Overloading
ï Sample Code
2. ï Experience has shown that the best way to develop and maintain large
programs is to construct it from smaller pieces(Modules)
ï This technique Called âDivide and Conquerâ
Bad Development Approach Wise Development Approach
main()
main() âąEaser To {
{ -----
----- ïŒDesign ----
----- ïŒBuild }
----- ïŒDebug
----- ïŒExtend function f1()
. ïŒModify {
. ïŒUnderstand ---
. ïŒReuse ---
---- ïŒBetter Organization }
-----
----- function f2()
Return 0; {
} ---
---
}
3. ï In FORTRAN Modules Known as Subprograms
ï In Pascal Modules known as Procedures &
Functions
ï In C++ Modules Known as Functions & Classes
ï Programs use new and âprepackagedâ modules
ï New: programmer-defined functions and classes
ï Prepackaged: from the standard library
4. ï Functions invoked by a functionâcall-statement which consist of itâs
name and information it needs (arguments)
ï Boss To Worker Analogy
ï A Boss (the calling/caller function) asks a worker (the called
function) to perform a task and return result when it is done.
Boss
Main
Worker
Worker Worker
Function Z
Function A Function B
Worker Worker
Note: usual main( ) Calls other
Function B1 Function B2 functions, but other functions
can call each other
5. âą Functions called by writing
functionName (argument);
or
functionName(argument1, argument2, âŠ);
âą Example
cout << sqrt( 900.0 );
âą sqrt (square root) function
âą The preceding statement would print 30
âą All functions in math library return a double
ï Function Arguments can be:
- Constant sqrt(9);
- Variable sqrt(x);
- Expression sqrt( x*9 + y) ;
sqrt( sqrt(x) ) ;
6. âą Calling/invoking a function
â sqrt(x);
â Parentheses an operator used to call function
âą Pass argument x
âą Function gets its own copy of arguments
â After finished, passes back result
Function Name argument Output
3
cout<< sqrt(9);
Parentheses used to enclose argument(s)
7. Math Library Functions Revisited
Method Description Example
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
point number
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Fig. 3.2 Math library functions.
8. ï Functions
ï Modularize a program
ï Software reusability
ï Call function multiple times
ï Local variables
ï Known only in the function in which they are defined
ï All variables declared in function definitions are local variables
ï Parameters
ï Local variables passed to function when called
ï Provide outside information
9. ï Function prototype
ï Tells compiler argument type and return type of function
ï int square( int );
ï Function takes an int and returns an int
ï Explained in more detail later
ï Calling/invoking a function
ï square(x);
ï Parentheses an operator used to call function
ï Pass argument x
ï Function gets its own copy of arguments
ï After finished, passes back result
10. ï Syntax format for function definition
returned-value-type function-name (parameter-list)
{
Declarations of local variables and Statements
}
ï Parameter list
ï Comma separated list of arguments
ï Data type needed for each argument
ï If no arguments, use void or leave blank
ï Return-value-type
ï Data type of result returned (use void if nothing
returned)
11. ï Example function
int square( int y )
{
return y * y;
}
ï return keyword
ï Returns data, and control goes to functionâs
caller
ï If no data to return, use return;
ï Function ends when reaches right brace
ï Control goes to caller
ï Functions cannot be defined inside other functions
12. // Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies
int square( int ); // function prototype data types of arguments and
return values. square
int main()
expects an int, and returns
{
an int.
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
Parentheses () cause function to be called.
cout << endl;
When done, it returns the result.
return 0; // indicates successful termination
} // end main
// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.
1 4 9 16 25 36 49 64 81 100
13. #include<iostream.h>
int square(int); // prototype Output
int cube(int); // prototype 1 square=1
main() 1 cube=1
{ int i; 2 square=4
for (int i=1;i<=10;i++){ 2 cube=8
.
.
cout<< i<< âsquare=â << square(i) << endl;
.
cout<< i<< âcube=â <<cube(i) << endl; .
} // end for 10 square=100
return 0; 10 cube=1000
} // end main function
int square(int y) //function definition
{
return y*y; // returned Result
}
int cube(int y) //function definition
{
return y*y*y; // returned Result
}
14. // Finding the maximum of three floating-point (real) numbers.
#include <iostream.h>
double maximum( double, double, double ); // function prototype
int main()
{
double number1, number2;
double number3; Function maximum takes 3
arguments (all double) and
cout << "Enter three real numbers: "; returns a double.
cin >> number1 >> number2 >> number3;
// number1, number2 and number3 are arguments to the maximum function call
cout << "Maximum is: "
<< maximum( number1, number2, number3 ) << endl;
return 0; // indicates successful termination
} // end main
// function maximum definition. x, y and z are parameters
double maximum( double x, double y, double z )
{
double max = x; // assume x is largest Enter three real numbers: 99.32 37.3 27.1928
if ( y > max ) // if y is larger, Maximum is: 99.32
max = y; // assign y to max
Enter three real numbers: 1.1 3.333 2.22
if ( z > max ) // if z is larger,
Maximum is: 3.333
max = z; // assign z to max
return max; // max is largest value
} // end function maximum
15. ï Function prototype contains
ï Function name
ï Parameters (number and data type)
ï Return type (void if returns nothing)
ï Only needed if function definition after
function call
ï Prototype must match function definition
ï Function prototype
double maximum( double, double, double );
ï Definition
double maximum( double x, double y, double
z )
{
âŠ
}
16. If the Function does not RETURN result, it is called void Function
#include<iostream.h>
void add2Nums(int,int);
main()
{ int a, b;
cout<<âenter tow Number:â;
cin >>a >> b;
add2Nums(a, b)
return 0;
}
void add2Nums(int x, int y)
{
cout<< x<< â+â << y << â=â << x+y;
}
17. If the function Does Not Take Arguments specify this with EMPT Y-LIST OR
write void inside
#include<iostream.h>
void funA();
void funB(void)
main()
{ Will be the same
funA(); in all cases
funB();
return 0;
}
void funA()
{
cout << âFunction-A takes no arqumentsnâ;
}
void funB()
{
cout << âAlso Function-B takes No argumentsnâ;
}
18. ï Local variables
ï Known only in the function in which they are
defined
ï All variables declared inside a function are local
variables
ï Parameters
ï Local variables passed to function when called (passing-
parameters)
ï Variables defined outside and before function main:
ï Called global variables
ï Can be accessible and used anywhere in the entire
program
19. ï Omitting the type of returned result defaults to int, but
omitting a non-integer type is a Syntax Error
ï If a Global variable defined again as a local variable in a
function, then the Local-definition overrides the Global
defining
ï Function prototype, function definition, and function call
must be consistent in:
1- Number of arguments
2- Type of those arguments
3-Order of those arguments
20. #include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
x = 11;
y = 22;
cout << âglobal x=â << x << endl;
cout << âGlobal y=â << y << endl;
s = add2(x, y);
cout << x << â+â << y << â=â << s;
cout<<endl;
cout<<ân---end of output---nâ;
return 0;
} global x=11
int add2(int x1,int y1)
{ int x; //local variables global y=22
x=44; Local x=44
cout << ânLocal x=â << x << endl; 11+22=33
return x1+y1;
}
---end of output---
21. int sum(int x, int y)
{
int result;
result = x+y;
}
ï this function must return an integer value as indicated in the header
definition (return result;) should be added
----------------------------------------------------------------------------------------
-
int sum (int n)
{ if (n==0)
return 0;
else
n+sum(n-1);
}
ï the result of n+sum(n-1) is not returned; sum returns an improper
result, the else part should be written as:-
else return n+sum(n-1);
22. void f(float a);
{
float a;
cout<<a<<endl;
}
ï ; found after function definition header.
ï redefining the parameter a in the function
void f(float a)
{
float a2 = a + 8.9;
cout <<a2<<endl;
}
23. void product(void)
{
int a, b, c, result;
cout << âenter three integers:â;
cin >> a >> b >> c;
result = a*b*c;
cout << âResult isâ << result;
return result;
}
ï According to the definition it should not return a value , but in the block (body) it
did & this is WRONG.
ï ï Remove return Result;
24. ï Call by value
âą A copy of the value is passed
ï Call by reference
âą The caller passes the address of the value
ï Call by value
ï Up to this point all the calls we have seen are call-by-value, a copy
of the value (known) is passed from the caller-function to the called-
function
ï Any change to the copy does not affect the original value in the
caller function
ï Advantages, prevents side effect, resulting in reliable software
25. ï Call By Reference
ï We introduce reference-parameter, to perform call by reference. The caller
gives the called function the ability to directly access the callerâs value, and to
modify it.
ï A reference parameter is an alias for itâs corresponding argument, it is stated in
c++ by âflow the parameterâs typeâ in the function prototype by an
ampersand(&) also in the function definition-header.
ï Advantage: performance issue
void function_name (type &);// prototype
main()
{
-----
------
}
void function_name(type ¶meter_name)
26. #include<iostream.h>
int squareVal(int); //prototype call by value function
void squareRef(int &); // prototype call by âreference function
int main()
{ int x=2; z=4;
cout<< âx=â << x << âbefore calling squareValâ;
cout << ânâ << squareVal(x) << ânâ; // call by value
cout<< âx=â << x << âAfter returningâ
cout<< âz=â << z << âbefore calling squareRefâ;
squareRef(z); // call by reference
cout<< âz=â << z<< âAfter returning squareRefâ
return 0;
} x=2 before calling squareVal
int squareVal(int a) 4
{ x=2 after returning
return a*=a; // callerâs argument not modified z=4 before calling squareRef
} z=16 after returning squareRef
void squarRef(int &cRef)
{
cRef *= cRef; // callerâs argument modified
}
27. ï rand function generates an integer between 0 and RAND-
MAX(~32767) a symbolic constant defined in <stdlib.h>
ï You may use modulus operator (%) to generate numbers within a
specifically range with rand.
//generate 10 random numbers open-range
int x;
for( int i=0; i<=10; i++){
x=rand();
cout<<x<<â â;
}
-------------------------------------------------------
//generate 10 integers between 0âŠâŠ..49
int x;
for( int i=0; i<10; i++){
x=rand()%50;
cout<<x<<â â;
}
28. //generate 10 integers between 5âŠ15
int x;
for ( int i=1; i<=10; i++){
x= rand()%11 + 5;
cout<<x<<â â;
}
------------------------------------
//generate 100 number as simulation of rolling a
dice
int x;
for (int i=1; i<=100; i++){
x= rand%6 + 1;
cout<<x<<â â;
}
29. ï the rand( ) function will generate the same set of random
numbers each time you run the program .
ï To force NEW set of random numbers with each new run
use the randomizing process
ï Randomizing is accomplished with the standard library
function srand(unsigned integer); which needs a
header file <stdlib.h>
Explanation of signed and unsigned integers:
ï int is stored in at least two-bytes of memory and can
have positive & negative values
ï unsigned int also stored in at least two-bytes of
memory but it can have only positive values 0âŠ..65535
30. #include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
int i;
unsigned num;
// we will enter a different number each time we run
cin>>num;
srand(num);
for(i=1; i<=5; i++)
cout<<setw(10)<< 1+rand()%6;
return 0;
}
Output for Multiple Runs
19ï 6 1 1 4 2 1
18ï 6 1 5 1 4 4 Different-set of Random
3ï 1 2 5 6 2 4 numbers
0ï 1 5 5 3 5 5
3ï 1 2 5 6 3 4
32. ï Main calls another functionâŠ..normal
ï A function calls another function2âŠ.normal
ï A function calls itself ?! Possible?? YES
ï A recursive function is one that call itself.
33. ï A recursive function is called to solve a problem
ï The function knows to solve only the simplest cases
or so-called base-cases
ï Thus if the function called with a base-case, it simply
returns a result. But if it is called with more complex
problem, the function divides the problem into two
conceptual pieces, one knows how to do, and another
doesn't know what to do.
ï The second case/piece must resemble the original
problem, but be a slightly simpler/smaller version of
the original problem
34. ï Thus the function launches (calls) a fresh
copy of itself to work on the smaller
problem âthis is related as a Recursive-
call/recursive step.
ï The function keeps dividing each new sub
problem into two conceptual pieces until
eventually terminates after converging on
the base-case.
ï The function thus recognize the base-case
and returns a result to the previous copy of
the way up the line until original call of the
function returns the final result to main.
35. 5! Final value=120
5!
5!=5*24=120 returned
5*4! 5*4!
4!=4*6=24 returned
4*3! 4*3!
3!=3*2=6 returned
3*2! 3*2!
2!=2*1=2 returned
2*1! 2*1!
1
1 1
36. //Recursive factorial Function
#include<iostream.h>
#include<iomonip.h>
unsigned lion factorial(unsigned long);//prototype
int main()
{
int num;
cout<<âenter a positive integer:â;
cin>>num;
cout<<âfactorial=â<<factorial(num);
return 0;
}
unsigned long factorial(unsigned long n)
{
if ( n <= 1) //the base case
return 1;
else
return n * factorial (n - 1);
}
37. ï Function overloading
ï Functions with same name and different
parameters
ï Should perform similar tasks
ï I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
ï A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters