0% found this document useful (0 votes)
12 views88 pages

Chapter 6 Function in C++ Progrogramming

Uploaded by

Murad Demelash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views88 pages

Chapter 6 Function in C++ Progrogramming

Uploaded by

Murad Demelash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 88

Chapter 6

Function in C++

Compiled By Dagne Walle 1


Functions
◼ Functions are building blocks of the programs.
◼ They make the programs more modular and easy to read and
manage.
◼ All C++ programs must contain the function main( ).
◼ The execution of the program starts from the function main( )
◼ Function Declaration
◼ Function Call
◼ Function Definition

2 Compiled By Dagne Walle


Functions and subprograms
◼ The Top-down design approach is based on dividing the main
problem into smaller tasks which may be divided into simpler
tasks, then implementing each simple task by a subprogram or a
function
◼ A C++ function or a subprogram is simply a chunk of C++ code
that has
❑ A descriptive function name, e.g.

◼ computeTaxes to compute the taxes for an employee

◼ isPrime to check whether or not a number is a prime


number
❑ A returning value

◼ The computeTaxes function may return with a double


number representing the amount of taxes
◼ The isPrime function may return with a Boolean value

3
(true or false) Compiled By Dagne Walle
Why Functions( methods/behaviors)
◼ Huge codes are difficult to understand and debug.
◼ Makes the code look simpler, neater and makes
your task easier.
◼ Re-usability of code.
◼ Boss to worker analogy: A boss (the calling
function or caller) asks a worker (the called
function) to perform a task and return (i.e., report
back) the results when the task is done
◼ Divide and conquer: Construct a program from
smaller pieces or components. Each piece more
manageable than the original program
Compiled By Dagne Walle 4
Terminologies

◼ Function Declaration/ Prototype:


int func(int , int);

◼ Function Definition:
int func ( int a, int b){
return (a + b);
}

Compiled By Dagne Walle 5


Terminologies
◼ The value passed to a method is called its
“argument”
◼ The variable which receives the arguments is called
“parameter”
◼ Parameters are declared inside the parenthesis and
we must declare the type of the parameter.

◼ Argument may be an expression but,


type (argument) = type (parameter)

Compiled By Dagne Walle 6


User-Defined C++ Functions
◼ Although C++ is shipped with a lot of standard
functions, these functions are not enough for all users,
therefore, C++ provides its users with a way to define
their own functions (or user-defined function)
◼ For example, the <cmath> library does not include a
standard function that allows users to round a real
number to the ith digits, therefore, we must declare
and implement this function ourselves

7 Compiled By Dagne Walle


How to define a C++ Function?
◼ Generally speaking, we define a C++ function in two
steps (preferably but not mandatory)
❑ Step #1 – declare the function signature in either a

header file (.h file) or before the main function of


the program
❑ Step #2 – Implement the function in either an

implementation file (.cpp) or after the main


function

8 Compiled By Dagne Walle


Function prototype
◼ The function prototype declaration contains
the three pieces of information about the
function that a caller needs to know:
❑ function's name,
❑ return type,
❑ argument type(s).

Compiled By Dagne Walle 9


Structure of a C++ Function?
◼ A C++ function consists of two parts
❑ The function header, and

❑ The function body

◼ The function header has the following syntax


<return value> <name> (<parameter list>)
◼ The function body is simply a C++ code enclosed
between { }

10 Compiled By Dagne Walle


User-defined C++ Function

Function
header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

11 Compiled By Dagne Walle


User-defined C++ Function

Function
Function body/definition
header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

12 Compiled By Dagne Walle


Function Prototype
◼ Every function should have a function
prototype.
◼ The function prototype specifies the type of the
value that the function returns (if any) and the
type, number, and order of the function's
arguments.
return-data-type function-name(argument
data types);
or void function-name(argument data types);
Compiled By Dagne Walle 13
Function Prototype

◼ The use of function prototypes permits error


checking of data types by the compiler.
◼ It also ensures conversion of all arguments passed
to the function to the declared argument data type
when the function is called.

Compiled By Dagne Walle 14


Function Signature/Declaration

◼ The function signature is actually similar to


the function header except in two aspects:
❑ The parameters’ names may not be specified in
the function signature
❑ The function signature must be ended by a
semicolon
◼ Example Unnamed Semicolon
Parameter ;

double computeTaxes(double) ;

15 Compiled By Dagne Walle


Function Prototype

#include <iostream>

void DisplayMenu(void);

int main( ) {
function prototype consisting of
<type> function name (types of parameters);

return 0; So void here means no return type or parameters


} expected. It is not required to use void here.

Compiled By Dagne Walle 16


Function Definition
◼ Define function header and function body
◼ Value-returning functions
return-data-type function-name(parameter list)
{
constant declarations
variable declarations

other C++ statements


return value
}
Compiled By Dagne Walle 17
Function Definition
◼ Non value-returning functions

void function-name(parameter list)


{
constant declarations
variable declarations

other C++ statements


}

Compiled By Dagne Walle 18


Function Definition
◼ The argument names in the function header are
referred to as formal parameters.
int FindMax(int x, int y)
{
int maximum;

if(x>=y)
maximum = x;
else
maximum = y;

return maximum;
}

Compiled By Dagne Walle 19


Function Definition
#include <iostream>
Function
void DisplayMenu(void); Definition:
int main() {
like a mini program
or sub program
return 0;
}

void DisplayMenu(void) {
cout << “*********** MENU **************\n”;
cout <<endl;
cout << “ 1. Man United” << endl;
cout << “ 2. Chelsea” << endl;
cout << “ 3. Arsenal” << endl;
cout << “ 4. Quit” << endl;
cout << endl;
cout << “Please choose 1, 2, 3 or 4 : “;
}
Compiled By Dagne Walle 20
Calling a function

◼ A function is called by specifying its name followed


by its arguments.
◼ Non-value returning functions:
function-name (data passed to function);
◼ Value returning functions:
results = function-name (data passed to function);

Compiled By Dagne Walle 21


Calling a function
#include <iostream.h>
int FindMax(int, int); // function prototype
int main()
{
int firstnum, secnum, max;
cout << "\nEnter two numbers: ";
cin >> firstnum >> secnum;
max=FindMax(firstnum, secnum); // the function is called here
cout << "The maximum is " << max << endl;
return 0;
}
◼ The argument names in the function call are
referred to as actual parameters
Compiled By Dagne Walle 22
Function Calling
#include <iostream>

void DisplayMenu(void);
Function call
int main() {
int response; from within
main()
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 : “;
Compiled By Dagne Walle 23
}
Why Do We Need Function Signature?
◼ For Information Hiding
❑ If you want to create your own library and share it with your
customers without letting them know the implementation
details, you should declare all the function signatures in a
header (.h) file.

◼ For Function Abstraction


❑ By only sharing the function signatures,
◼ Improve function performance

◼ make the customers focus on the purpose of the function, not its
24 implementation Compiled By Dagne Walle
Example
#include <iostream>
#include <string> double computeTaxes(double income)
using namespace std; {
if (income<5000) return 0.0;
// Function Signature return 0.07*(income-5000.0);
double getIncome(string); }
double computeTaxes(double);
void printTaxes(double); double getIncome(string prompt)
int main() {
{ cout << prompt;
// Get the income; double income;
double income = getIncome("Please cin >> income;
enter the employee income: ");
return income;
// Compute Taxes }
double taxes = computeTaxes(income); void printTaxes(double taxes)
{
// Print employee taxes cout << "The taxes is $" << taxes <<
printTaxes(taxes); endl;
} }

25 Compiled By Dagne Walle


User-Defined Functions
◼ There are two ways to share data among
different functions
❑ Using global variables (very bad practice!)
❑ Passing data through function parameters

◼ Value parameters, call by value which means that


a function receives copies of the values of its
arguments
◼ Reference parameters

26 Compiled By Dagne Walle


C++ Variables
◼ A variable is a place in memory that has
❑ A name or identifier (e.g. income, taxes, etc.)

❑ A data type (e.g. int, double, char, etc.)

❑ A size (number of bytes)

❑ A scope (the part of the program code that can use it)

◼ Global variables – all functions can see it and using it

◼ Local variables – only the function that declare local


variables see and use these variables
❑ A life time (the duration of its existence)

◼ Global variables can live as long as the program is


executed
◼ Local variables are lived only when the functions that
define these variables are executed
27 Compiled By Dagne Walle
C++ Variables
◼ A variable is a place in memory that has
❑ A name or identifier (e.g. income, taxes, etc.)

❑ A data type (e.g. int, double, char, etc.)

❑ A size (number of bytes)

❑ A scope (the part of the program code that can use it)

◼ Global variables – all functions can see it and using it

◼ Local variables – only the function that declare local


variables see and use these variables
❑ A life time (the duration of its existence)

◼ Global variables can live as long as the program is


executed
◼ Local variables are lived only when the functions that
define these variables are executed
28 Compiled By Dagne Walle
Using Global Variables
#include <iostream>
int main()
int x = 0;
{
void f1()
f2();
{
cout << x << endl;
x++;
}
}
void f2() {
Output:?
x+=4;
f1();
}
29 Compiled By Dagne Walle
What is Bad About Using Global Vairables?
◼ Not safe!
❑ If two or more programmers are working together in a
program, one of them may change the value stored in the
global variable without telling the others who may depend
in their calculation on the old stored value!

◼ Against The Principle of Information Hiding!


❑ Exposing the global variables to all functions is against the
principle of information hiding since this gives all functions
the freedom to change the values stored in the global
30 Compiled By Dagne Walle
variables at any time (unsafe!)
Local Variables
◼ Local variables are declared inside the function body
and exist as long as the function is running and
destroyed when the function exit
◼ You have to initialize the local variable before using it
◼ If a function defines a local variable and there was a
global variable with the same name, the function uses
its local variable instead of using the global variable

31 Compiled By Dagne Walle


Using Global and Local Variables
#include <iostream> int main()
int x; // Global variable {
void fun(); // function x = 4;
signature fun();
void fun() cout << x << endl;
{ }
int x = 10; // Local
variable Output:?
cout << x << endl;
}

32 Compiled By Dagne Walle


Parameters
◼ Function Parameters come in three flavors:
❑ Value parameters – which copy the values of the
function arguments
❑ Reference parameters – which refer to the function
arguments by other local names and have the
ability to change the values of the referenced
arguments
❑ Constant reference parameters – similar to the
reference parameters but cannot change the values
of the referenced arguments

33 Compiled By Dagne Walle


Calling a function by value
◼ The function receives a copy of the actual
parameter values.
◼ The function cannot change the values of the
actual parameters.

Compiled By Dagne Walle 34


Value Parameters
◼ This is what we use to declare in the function signature
or function header, e.g.
int max (int x, int y);
❑ Here, parameters x and y are value parameters
❑ When you call the max function as max(4, 7), the values 4
and 7 are copied to x and y respectively
❑ When you call the max function as max (a, b), where a=40
and b=10, the values 40 and 10 are copied to x and y
respectively
❑ When you call the max function as max( a+b, b/2), the
values 50 and 5 are copies to x and y respectively
◼ Once the value parameters accepted copies of the
corresponding arguments data, they act as local
35 variables! Compiled By Dagne Walle
Value Parameters
#include <iostream> int main()
int x; // Global variable {
void fun(int x) x = 4;
{ fun(x/2+1);
cout << x << endl; cout << x << endl;
x=x+5; }
} Output:?

36 Compiled By Dagne Walle


Reference Parameters
◼ As we saw in the last example, any changes in the
value parameters don’t affect the original function
arguments
◼ Sometimes, we want to change the values of the
original function arguments or return with more than
one value from the function, in this case we use
reference parameters
❑ A reference parameter is just another name to the original
argument variable
❑ We define a reference parameter by adding the & in front of
the parameter name, e.g.
double update (double & x);

37 Compiled By Dagne Walle


References
◼ A reference is an automatically dereferenced
pointer
◼ Syntax of reference declaration:
Type& refname = variable;

◼ Semantics: refname becomes another name (or


alias) for variable.
◼ Any change to the value of variable causes the
same change to refname, and vice versa.

Compiled By Dagne Walle 38


Calling a function by reference

◼ Very useful when we need a function which


"returns more than one value".
◼ The formal parameter becomes an alias for the
actual parameter.
◼ The function can change the values of the actual
parameters.

Compiled By Dagne Walle 39


Calling a function by reference
#include <iostream.h>
void newval(float&, float&); // function prototype
int main()
{
float firstnum, secnum;
cout << "Enter two numbers: ";
cin >> firstnum >> secnum;
newval(firstnum, secnum);
cout << firstnum << secnum << endl;
return 0;
}

void newval(float& xnum, float& ynum)


{
xnum = 89.5;
ynum = 99.5;
}
Compiled By Dagne Walle 40
Reference Parameters
#include <iostream> int main()
void fun(int &y) {
{ int x = 4; // Local
cout << y << endl; variable
y=y+5; fun(x);
} cout << x << endl;
}
Output:?

41 Compiled By Dagne Walle


Illustration of References
Statements Outcome
int x=17; x=17
int& xref = x;
cout<<“x=“<<x<<endl;
xref=17
cout<<“xref=“<<xref<<endl;
x=x+5; x=22
cout<<“x=“<<x<<endl;
cout<<“xref=“<<xref<<endl;
xref=22
xref = xref-10; x=12
cout<<“x=“<<x<<endl;
cout<<“xref=“<<xref<<endl;
xref=12

Compiled By Dagne Walle 42


References and Function Call by
Reference
void swap(int x, int y){ void swap(int& x, int& y){
int tmp=x; x=y; y=tmp; int tmp=x; x=y; y=tmp;
} }
int x=5; int y=10; int x=5; int y=10;
swap(x,y); swap(x,y);
cout<<x<<“, “<<y; cout<<x<<“, “<<y;
Outcome: Outcome:
5, 10 // no swap 10, 5 // it did swap

Compiled By Dagne Walle 43


Look alike but exhibit different characters
Compiled By Dagne Walle 44
Polymorphism
◼ Refers to ‘one name having many forms’, ‘one
interface doing multiple actions’.
◼ In C++, polymorphism can be either
❑ static polymorphism or
❑ dynamic polymorphism.

◼ C++ implements static polymorphism through


❑ overloaded functions
❑ overloaded operators
Compiled By Dagne Walle 45
Polymorphism
◼ Derived from the Greek many forms

◼ Single name can be used for different purposes

◼ Different ways of achieving the polymorphism:

1. Function overloading

2. Operator overloading

3. Dynamic binding

Compiled By Dagne Walle 46


Function Overloading

◼ C++ provides the capability of using the same


function name for more than one function
(function overloading).
◼ The compiler must be able to determine which
function to use based on the number and data
types of the parameters.

Compiled By Dagne Walle 47


Function Overloading

 C++ enables several functions of the same name to be


defined, as long as they have different signatures.
 This is called function overloading.
 The C++ compiler selects the proper function to call by
examining the number, types and order of the
arguments in the call.

Compiled By Dagne Walle 48


Function Overloading

 A function is overloaded when same name is given to


different function.
 The two functions with the same name will differ at
least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance

Compiled By Dagne Walle 49


Function overloading

◼ To print six data types we could write:


void PrintInt(int n){
cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
}
void PrintDouble(double d){
cout<<“***Debug***” << endl;
cout<<“Value is ” << d << endl;
}
Compiled By Dagne Walle 50
Function overloading

void PrintChar(char n){


cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
}
void PrintFloat(float n){
cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
}

Compiled By Dagne Walle 51


The solution to previous problem
◼ Instead of having different names for all these similar
functions we can use function overloading by giving
them all the same name print
void Print(int n)
{
cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
}
void Print(char n){
cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
} Compiled By Dagne Walle 52
The solution continued

void Print(char n){


cout<<“***Debug***” << endl;
cout<<“Value is ” << n << endl;
}
void Print(float x){
cout<<“***Debug***” << endl;
cout<<“Value is ” << x << endl;
}

Compiled By Dagne Walle 53


Maximum of two integers
◼ Here is a small function that you might write to find
the maximum of two integers.

int max(int a, int b)


{
if (a > b)
return a;
else
return b;
}

Compiled By Dagne Walle 54


Maximum of two doubles
◼ Here is a small function that you might write to find
the maximum of two doubles.

double max(double a, double b)


{
if (a > b)
return a;
else
return b;
}

Compiled By Dagne Walle 55


Compiled By Dagne Walle 56
Following code fragment overloads a function
name prnsqr( ).

void prnsqr (int i); //overloaded for integer #1

void prnsqr (char c); //overloaded for character #2

void prnsqr (float f); //overloaded for floats #3

void prnsqr (double d); //overloaded for double floats #4

Compiled By Dagne Walle 57 57


void prnsqr (int i)
{
cout<<“Integer”<<i<<“’s square is”<<i*i<<“\n”;
}
void prnsqr (char c);
{
cout <<“No Square for characters”<<“\n”;
}
void prnsqr (float f)
{
cout<<“float”<<f <<“’s square is”<<f *f<<“\n”;
}
void prnsqr (double d)
{
cout <<“Double float”<<d<<“’s square is”<<d*d<<“\n’;}
Compiled By Dagne Walle 58 58
Overloading
◼ Overloading – A name having two or more
distinct meanings

◼ Overloaded function - a function having


more than one distinct meanings

◼ Overloaded operator - When two or more


distinct meanings are defined for an operator

Compiled By Dagne Walle 59


Overloading
◼ Operator overloading is inbuilt in C and C++.
◼ ‘-’ can be unary as well as binary
◼ ‘*’ is used for multiplication as well as
pointers
◼ ‘<<‘, ‘>>’ used as bitwise shift as well as
insertion and extraction operators
◼ All arithmetic operators can work with any
type of data

Compiled By Dagne Walle 60


Inline function
◼ An inline function is a function that
expanded in line when it is invoked. That is
the compiler replaces the function call with
the corresponding function code .
◼ Syntax:
inline function-header
{
Function body
}
Compiled By Dagne Walle 61
Inline function
#include <iostream.h>
#include<conio.h>
int multiply(int);
int main( ){
int x;
cout<< "\n Enter the Input Value: ";
cin>>x;
cout<<"\n The Output is: " << multiply(x);
}
inline int multiply(int x1)
{
return 5*x1;
}
Compiled By Dagne Walle 62
Recursion Function
◼ Recursive functions
❑ Functions that call themselves
❑ Can only solve a base case
◼ If not base case
❑ Break problem into smaller problem(s)
❑ Launch new copy of function to work on the smaller
problem (recursive call/recursive step)
◼ Slowly converges towards base case
◼ Function makes call to itself inside the return statement
❑ Eventually base case gets solved
◼ Answer works way back up, solves entire problem
63 Compiled By Dagne Walle
Recursion

◼ Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
❑ Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
4! = 4 × 3 × 2 × 1
❑ Base case (1! = 0! = 1)

64 Compiled By Dagne Walle


Recursion
int main() {
int nFact = factorial(5);
cout << "5! = " << nFact << endl;
return 0;
}
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
65 Compiled By Dagne Walle
Recursion
Write a C++ function using recursion to sum the numbers from 1 to n
#include <iostream.h>
int sum(int);
void main(){
int x;
cout<<"Enter a number to calculate the sum ";
cin>>x;
cout<<“Sum of the series “<<sum(x)<<endl;
}
int sum(int n){
if (n==1)
return 1;
else
return n+sum(n-1);
}
66
Recursion
Write a C++ function using recursion to sum the numbers from x to y
#include <iostream.h>
int sum(int,int);
void main(){
int x,y;
cout<<"Enter two numbers to calculate the sum ";
cin>>x>>y;
cout<<“Sum of the series “<<sum(x,y)<<endl;
}
int sum (int a, int b){
if (a==b)
return b;
else
return b+sum(a,b-1);
}
67
Sum OF Digits
nt main() {
int n = getInteger("Enter an integer: ");
int digitSum = sumOfDigitsOf(n);
cout << "Digit sum: " << digitSum << endl;
return 0;}
int sumOfDigitsOf(int n) { int n
int result = 0;
while (n > 0) {
result += (n % 10);
n /= 10;}
return result;
}
68 Compiled By Dagne Walle
Using Recursion: Fibonacci Series
◼ Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
❑ Each number sum of two previous ones
❑ Example of a recursive formula:
◼ fib(n) = fib(n-1) + fib(n-2)
◼ C++ code for Fibonacci function
long fibonacci( long n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) +
fibonacci( n – 2 );
}

69 Compiled By Dagne Walle


Math Library Functions

◼ Perform common mathematical calculations


❑ Include the header file <cmath>
◼ Example
cout << sqrt( 900.0 );
❑ sqrt (square root) function The preceding statement
would print 30
❑ All functions in math library return a double

70 Compiled By Dagne Walle


Math Library Functions
◼ Function arguments can be
❑ Constants
◼ sqrt( 4 );
❑ Variables
◼ sqrt( x );
❑ Expressions
◼ sqrt( sqrt( x ) ) ;
◼ sqrt( 3 - 6x );

71 Compiled By Dagne Walle


M e tho d De sc rip tio n Exa m p le
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 M a th lib ra ry func tio ns.
72 Compiled By Dagne Walle
C++ Math Functions
#include <iostream>
#include <cmath>
int main()
{
// Getting a double value
double x;
cout << "Please enter a real number: ";
cin >> x;
// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;
}

73 Compiled By Dagne Walle


Defining a Function Template

◼ In C++ a function template allows you to write a


function definition with “blanks” left in the
definition to be filled in by the calling code.
◼ Most often the “blanks” to be filled in are the
names of the data types.
◼ Here is a function template for the Print function
met earlier

Compiled By Dagne Walle 74


Function template definition

template<class someType>
void Print (SomeType val)
{
cout<<“***Debug***” << endl;
cout<<“Value is ” << val << endl;
}

Compiled By Dagne Walle 75


Function templates continued

◼ This function template begins with template<class


SomeType>, and SomeType is known as the
template parameter.
◼ You can use any identifier for the template
parameter, we used SomeType in this example

Compiled By Dagne Walle 76


Function Template Syntax

◼ Syntax

template<templateparamList>
FunctionDefinition

Compiled By Dagne Walle 77


A Template Function for Maximum
This template function can be used with many data
types.

template <class Item>


Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}

Compiled By Dagne Walle 78


A Template Function for Maximum
When you write a template function, you choose a
data type for the function to depend upon...

template <class Item>


Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}

Compiled By Dagne Walle 79


A Template Function for Maximum

A template prefix is also needed immediately before


the function’s implementation:
template <class Item>
Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}

Compiled By Dagne Walle 80


Using a Template Function

Once a template function is defined, it may be used


with any adequate data type in your program...
template <class Item>
Item maximum(Item a, Item b) cout << maximum(1,2);
{ cout << maximum(1.3, 0.9);
if (a > b) ...
return a;
else
return b;
}

Compiled By Dagne Walle 81


Finding the Maximum Item in an
Array
Here’s another function that can be made more
general by changing it to a template function:
int array_max(int data[ ], size_t n)
{
size_t i;
int answer;

assert(n > 0);


answer = data[0];
for (i = 1; i < n; i++)
if (data[i] > answer) answer = data[i];
return answer;
}
Compiled By Dagne Walle 82
Finding the Maximum Item in an
Array
Here’s the template function:

template <class Item>


Item array_max(Item data[ ], size_t n)
{
size_t i;
Item answer;

assert(n > 0);


answer = data[0];
for (i = 1; i < n; i++)
if (data[i] > answer) answer = data[i];
return answer;
}
Compiled By Dagne Walle 83
Summary

A template function depends on an underlying data


type.

Compiled By Dagne Walle 84


Question
◼ Write a program using function which display
“Welcome to C++”. Call this function from main( ).
◼ Write a program using function which asked two
integer numbers from user and return its sum. Call this
function from main( ) and print the results in main( )

85
Question

◼ Write a program using function which accept two


integers as an argument and return its sum. Call this
function from main() and print the results in main( )
◼ Write a program using function which accept two
integers as an argument and print the sum. Call this
function from main()

86
To calculate the area of circle, rectangle and
triangle using function overloading.
◼ S1: Start the program.
◼ S2: Declare the class name as fn with data members and member
functions.
◼ S3: Read the choice from the user.
◼ S4: Choice=1 then go to the S5.
◼ S5: The function area() to find area of circle with one integer
argument.
◼ S6: Choice=2 then go to the S7.
◼ S7: The function area() to find area of rectangle with two integer
argument.
◼ S8: Choice=3 then go to the S9.
◼ S9: The function area() to find area of triangle with three
arguments, two as Integer and one as float.
◼ S10: Choice=4 then stop the program.
Compiled By Dagne Walle 87
End Of Chapter

? QUESTIONS ?

Compiled By Dagne Walle 88

You might also like