Chapter 3 Function

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

CHAPTER THREE

FUNCTION
CHAPTER THREE
FUNCTION
• A function is a collection of statements that
performs a specific task.
• Functions are commonly used to break a problem
down into small manageable pieces.
• Another reason to write functions is that they
simplify programs.
• This benefit of using functions is known as code
reuse because you are writing the code to perform a
task once and then reusing it each time you need to
perform the task. 2
Cont’d…

3
Defining Functions
• A function definition contains the statements that
make up the function.
• When creating a function, you must write its
definition.
• All function definitions have the following parts:
 Return type:
 Name:
 Parameter list:
 Body:

4
FUNCTION DEFINITION
• Return type: A function can send a value to the part
of the program that executed it. The return type is the
data type of the value that is sent from the function.
• Name: You should give each function a descriptive
name. In general, the same rules that apply to
variable names also apply to function names.
• Parameter list: The program can send data into a
function. The parameter list is a list of variables that
hold the values being passed to the function.
• Body: The body of a function is the set of statements
that perform the function’s operation. They are
enclosed in a set of braces. 5
Structure of a function

6
Cont’d…
• A function declaration is simply the function’s header,
followed by a semicolon. A function definition is the
complete function: header and body. A function
declaration is also called a function prototype.
• A function declaration is like a variable declaration;
its purpose is simply to provide the compiler with all
the information it needs to compile the rest of the
file. The compiler does not need to know how the
function works (its body).
• It only needs to know the function’s name, the
number and types of its parameters, and its return
type. 7
Cont’d…
• Function Declarations:
• A function declaration tells the compiler about a
function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:
• return_type function_name( parameter list );
• For the above defined function max(), following is the
function declaration:
• int max(int num1, int num2);Parameter names are
not importan in function declaration only their type is
required, so following is also valid declaration:
• int max(int, int); 8
Parameters and arguments
• The variables that are listed in the function’s
parameter list are called formal parameters or
formal arguments. They are local variables that
exist only during the execution of the function.
• The variables that are listed in the function’s calls
are called the actual parameters or actual
arguments. Like any other variable in the main
program, they must be declared before they are
used in the call.

9
Cont’d…
// function example
#include <iostream.h>
int addition (int a, int b)
{
int r; r=a+b; parameter list
return r;
} function name
int main ()
{ function call
int z; argument
z = addition (5,3);
cout << "The result is " << z;
} 10
FUNCTION PROTOTYPE
• A function prototype eliminates the need to place a
function definition before all calls to the function.
• Before the compiler encounters a call to a particular
function, it must already know the function’s return
type, the number of parameters it uses, and the type
of each parameter.
• The prototype looks similar to the function definition ,
except there is a semicolon at the end.
• Function prototypes are also known as function
declarations.
• You must place either the function definition or the
function prototype ahead of all calls to the function.
11
Advantages of Function Prototypes in C++
• Use of function prototypes in C++ offers following advantages:
• Prototypes enables the compilers to provide stronger type
checking.
• Because of the use of prototypes, the compiler can find and
report any questionable type conversions between the
arguments used to call a function and the types of its
(function) parameters
• Because of the use of prototypes, the compiler can also catch
differences between the number of arguments used to call a
function and the number of parameters in the functions
• Function prototypes help to trap bugs before they occur
• Function prototypes help to verify that the program is working
correctly by not allowing functions to be called with
mismatched arguments 12
Example
#include <iostream.h>
int mul(int,int); // FUNCTION PROTOTYPE
int main()
{
int a,b,c;
cout<<”Enter two values <<endl”;
cin>>a>>b;
c=mul(a,b);
cout<<”The Product is “<<c;
}
int show(int x,int y)
{
int z;
z=x * y;
return z; 13
CALLING FUNCTION
• A function call is a statement that causes a function
to execute.
• A function is executed when it is called. Function
main is called automatically when a program starts,
but all other functions must be executed by function
call statements.
• When a function is called, the program branches to
that function and executes the statements in its
body. Let’s look at Program 6-1, which contains two
functions: main and displayMessage.

14
Cont’d…
// This program has two functions: main and displayMessage
#include <iostream.h>
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
int main()
{
cout << "Hello from main.\n";
displayMessage();
cout << "Back in function main again.\n";
return 0; 15
Cont’d…

16
Cont’d…
#include <iostream.h>
void first()
{
cout << "I am now inside the function first.\n";
}
void second()
{
cout << "I am now inside the function second.\n";
}
int main()
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << "Back in function main again.\n";
return 0; 17
Cont’d…

18
Notes on passing arguments

• The numbers of actual arguments and formals argument


should be same. (Exception: Function Overloading)
• The type of first actual argument should match the type
of first formal argument. Similarly, type of second
actual argument should match the type of second formal
argument and so on.
• You may call function without passing any argument.
The number(s) of argument passed to a function
depends on how programmer want to solve the problem.
• In above program, both arguments are of int type. But
it's not necessary to have both arguments of same type.

19
Parameter passing mechanism
There are three parameter passing mechanisms for
passing arguments to functions such as pass by value
and pass by reference.
1. Passing argument by value or call by value
• The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function. In this case,
changes made to the parameter inside the function
have no effect on the argument.
• when calling a function, what is passed to the
function are the values of these arguments on the
moment of the call, which are copied into the 20
Cont’d…
#include <iostream.h> // function declaration
void swap(int x, int y);
int main ()
{
// local variable declaration:
int a = 100; int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int x, int y)
{
int temp;
temp=x;/*save the value of x */
x=y;//put y in to x
y=temp;//put x in to y 21
Passing argument by reference

Call by Reference:-
• The formal parameters must be of type reference
• When we pass parameters by reference the formal parameters
becomes like an alias variable to the formal parameters
• To pass arguments by reference, the function call is similar to
that of call by value. Ex swap(a,b)
• In the function decelerator the formal parameters are
preceded by the ‘&’ operator.
• It is possible to return more than one value from a function to
the main program
• Any changes to the formal parameters are automatically
reflected back to the actual parameters in the main program.
• Using this method no duplicate set of variables are crated.
22
Cont’d…
#include <iostream.h>
void fun (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
fun (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0; 23
Call by address
• In C++ it is possible to call a function by passing
address this technique is known as call by address.
• In all by address technique the formal parameters
must be a pointer type and they receive the
addresses of actual parameters.
• Any changes to the formal parameters are
automatically reflected back to the actual
parameters in the main program.
• It is possible to make a function to return more than
one value to the calling program
• The address can be generated by using address
operator &.
24
Cont’d…
void main( )
{
void square ( int *, int *); // function prototype
int a,b;
cout<<”enter value of a and b”;
cin>>a>>b;
square(&a, &b); // function call, a and b are actual arguments.
cout<<a<<b // square values
}
void squre (int *p1, int *p2)
{
*p1=(*p1) * (*p1) ;
*p2=(*p2) * (*p2) ;
}

25
Returning values by value
a function can take parameters and also can return
value.
• In the following example, this function show() used
in this program takes two parameters and returns
the sum of the parameters

26
Cont’d…
#include <iostream.h>
int mul(int, int); // FUNCTION PROTOTYPE
void main()
{
int a,b,c;
cout<<”Enter two values <<endl”;
cin>>a>>b;
c=mul(a,b);
cout<<”The Product is “<<c; The variable a , b are known as
} actual parameters whose
int show(int x, int y) values are copied to the dummy
{ variables x and y. The result of
int z; the multiplication is stored in z
z=x * y; and this value is copied to c.
return z; 27
Returning values by references
A function can also return by reference.

28
Cont’d…
#include<iostream.h>
This function returns reference to a
#include<iomanip.h>
int & check(int & a,int &b)
or b. The function check returns
{
reference to either x or y based on
if(a>b) the condition. Thus whatever value
return a; is given as input for x and y the
else function call assigns the value of x
return b; to the reference that is returned
} thus the cout statement displays
void main( ) the value of x twice.
{
int x,y;
cout<<”enter two values “ <<endl;
cin>>x>>y;
check(x,y)=0;
cout<<”After executing check function “<<endl;
cout<<x <<”\t”<<y; 29
Void function
• functions that do not have a return type. These
functions do not use a return statement to return a
value.
• In this case, the type to be used is void, which is a
special type to represent the absence of value.
• The return 0; statement causes the value 0 to be
returned when the main function finishes executing.
• It isn’t necessary for all functions to return a value,
however.
• Some functions simply perform one or more
statements which follows terminate. These are called
void functions. 30
Cont’d…
#include <iostream.h>
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
int main()
{
cout << "Hello from main.\n";
displayMessage();
cout << "Back in function main again.\n";
return 0; 31
What is Inline functions
• When you define a function, normally the compiler
creates just one set of instructions in memory.
• 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.
• If you call the function 10 times, your program
jumps to the same set of instructions each time.
This means there is only one copy of the function,
not 10.

32
Cont’d…
• There is some performance overhead in jumping in
and out of functions. 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.

33
Cont’d…
• If a function is declared with the keyword inline, the
compiler does not create a real function: it copies
the code from the inline function directly into the
calling function. No jump is made; it is just as if you
had written the statements of the function right
into the calling function. When the function is defined
Inline, the C++ compiler puts the
function body inside the calling
inline function-prototype function. You can define function as
{ Inline when the function body is
function body small and need to be called many
times, thus reduces the overhead in
} calling a function like passing
values, passing control, returning
values, returning control. 34
Cont’d…
Inline functions have some restrictions.
• Function containing looping structure cannot be
made inline.
• Recursive functions cannot be made inline.
• A function with many lines of coding cannot be
made inline.
• The disadvantage of in-line functions is that if they
are too large and called to often, the program grows
larger.
• For this reason, in general only short functions are
declared as in-line functions.
35
Cont’d…
• In many places we create the functions for small
work/functionality which contain simple and less
number of executable instruction.
• When a normal function call instruction is
encountered, the program stores the memory address
of the instructions immediately following the function
call statement, loads the function being called into
the memory, copies argument values, jumps to the
memory location of the called function, executes the
function codes, stores the return value of the
function, and then jumps back to the address of the
instruction that was saved just before executing the
called function. Too much run time overhead. 36
Inline function
When inline functions are used, the overhead of function call is
eliminated. Instead, the executable statements of the function are
copied at the place of each function call. This is done by the compiler.
#include <iostream.h>
inline int sqr(int x)
{
int y; Here, the statement b = sqr(a) is a
y = x * x; function call to sqr(). But since we have
return y; declared it as inline, the compiler
} replaces the statement with the
int main() executable stmt of the function (b = a
{ *a)
int a =3, b; Please note that, inline is a request to
b = sqr(a); the compiler. If it is very complicated
cout <<b; function, compiler may not be able to
return 0; convert it to inline 37
}
INLINE FUNCTION
#include<iostream.h>
inline double computeGross(double hours, double rate)
{
return(hours * rate);
}
int main()
}
double hrsWorked=37.5, rateOfPay=12.45, gross;
gross = computeGross(hrsWorked, rateOfPay);
cout << endl << "Gross pay is " << gross << endl;
return 0;
38
}
Cont’d…
#include < iostream.h >
#include<iomanip.h>
inline int even(int x){
if (x %2==0)
return 1;
else
return 0;
} int main( ){
int a;
cout<<”Enter any number”<<endl;
cin>>a;
if(even(a))
cout<<”EVEN NUMBER”;
else
cout<<”ODD NUMBER”; 39
USING DEFAULT PARAMETERS
• Default arguments are passed to parameters
automatically if no argument is provided in the
function call.
• It’s possible to assign default arguments to function
parameters. A default argument is passed to the
parameter when the actual argument is left out of
the function call.
• The default arguments are usually listed in the
function prototype.
• Default arguments are literal values or constants
with an = operator in front of them, appearing after
the data types listed in a function prototype. 40
Cont’d…
Here is an example:
void showArea(double = 20.0, double = 10.0);
• If a function does not have a prototype, default
arguments may be specified in the function header.
The showArea function could be defined as follows:
void showArea(double length = 20.0, double width
= 10.0)
{
double area = length * width;
cout << "The area is " << area << endl;
} 41
Cont’d…
// This program demonstrates default function arguments.
#include <iostream.h> #include <iostream.h>
// Function prototype with default arguments int divide (int a, int b=2)
void displayStars(int = 10, int = 1); {
int r;
int main(){
r=a/b;
displayStars(); // Use default values for cols and rows. return (r);
cout << endl; }
displayStars(5); // Use default value for rows. int main ()
cout << endl; {
displayStars(7, 3); // Use 7 for cols and 3 for rows. cout << divide (12) << '\n';
cout << divide (20,4) << '\n';
return 0;}
return 0;
void displayStars(int cols, int rows) { }
// Nested loop. The outer loop controls the rows
// and the inner loop controls the columns.
for (int down = 0; down < rows; down++){
for (int across = 0; across < cols; across++)
cout << "*";
cout << endl;
}} 42
Cont’d…
Here is a summary of the important points about
default arguments:
 The value of a default argument must be a literal
value or a named constant.
 When an argument is left out of a function call
(because it has a default value), all the arguments
that come after it must be left out too.
 When a function has a mixture of parameters both
with and without default arguments, the
parameters with default arguments must be
declared last.
43
Overload function
• In C++ two different functions can have the same
name if their parameter types or number are
different.
• That means that you can give the same name to
more than one function if they have either a
different number of parameters or different types in
their parameters. For example:
float volume(int x);
float volume(int x,int y);
float volume(int z, int w, int y);
44
Cont’d…

#include<iostream.h> sum(a,b,c);
#include<iomanip.h> }
void sum(int,int); void sum(int x,int y)
void sum(int,int,int); {
void main() int z;
{ z=x+y;
int a ,b, c ; cout<<z;
cout<<”Enter three values }
“<<endl; void sum(int x,int y,int z)
cin>>a>>b>>c; {
cout<<”Calling the function int r;
with two parameters”<<endl; r=x+y+z;
sum(a,b); cout<<r;
Cout<<”Calling the function } 45
Cont’d…
// overloaded function
#include <iostream.h>
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
out << "\n";
cout << operate (n,m);
cout << "\n"; 46
Recursive Function

• A recursive function is a function that calls itself


during its execution. This enables the function to
repeat itself several times, outputting the result and
the end of each iteration.
• Recursive is the property that functions have to be
called by themselves. It is useful for some tasks,
such as sorting elements, or calculating the factorial
of numbers
Below is an example of a recursive function.
n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
47
example

48
Cont’d…
#include <iostream.h>
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0; 49
Cont’d…
#include <iostream> # include <iostream.h>
int factorial(int); int Fibonacci(int n)
/* Fibonacci: recursive version */
int main() {
{ if(n<=0) return 0;
int n; else if(n==1) return 1;
cout<<"Enter a number to find factorial: "; else
{
cin>>n; return Fibonacci(n-1)+Fibonacci(n-2);
cout<<"Factorial of "<<n<<" = “ }
<<factorial(n); }
int main()
return 0;
{
} int a;
int factorial(int n) { if (n>1) cin>>a;
{ cout<<Fibonacci(a);
}
return n*factorial(n-1); }
else
{
return 1; 50
Arrays as Function Arguments
• To pass an array as an argument to a function, pass
the name of the array.
• functions could be written to put values in an array,
display an array’s contents on the screen, total all of
an array’s elements, or calculate their average.
Usually, such functions Passing an accept an array as
an argument.
• When a single element of an array is passed to a
function, it is handled like any other variable.

51
Cont’d…
#include <iostream.h>
void display(int marks[5]);
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
void display(int m[5])
{
cout<<"Displaying marks: "<<endl;
for (int i = 0; i <5; ++i)
{ cout<<"Student "<<i+1<<": "<<m[i]<<endl;
52
}}
Cont’d..
// This program demonstrates that an array element is passed to a function like any other
variable.
#include <iostream.h>
void showValue(int); // Function prototype
int main()
{
const int SIZE = 8;
int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int index = 0; index < SIZE; index++)
showValue(numbers[index]);
return 0;
}
void showValue(int num)
{
cout << num << " "; } 53
Cont’d…
// This program demonstrates the showValues function being
// used to display the contents of two arrays.
#include <iostream>
void showValues(int [], int); // Function prototype
int main(){
const int SIZE1 = 8; // Size of set1 array
const int SIZE2 = 5; // Size of set2 array
int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[SIZE2] = {2, 4, 6, 8, 10};
// Pass set1 to showValues.
showValues(set1, SIZE1);
// Pass set2 to showValues.
showValues(set2, SIZE2);
return 0; }
void showValues(int nums[], int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;} 54
Pointers as Function Parameters
• A pointer can be used as a function parameter. It
gives the function access to the original argument,
much like a reference parameter does.
• A reference variable acts as an alias to the original
variable used as an argument.
• This gives the function access to the original
argument variable, allowing it to change the
variable’s contents.
• When a variable is passed into a reference
parameter, the argument is said to be passed by
reference. 55
Cont’d…
• Another way to pass an argument by reference is to
use a pointer variable as the parameter.
• Admittedly, reference variables are much easier to
work with than pointers.
• Reference variables hide all the “mechanics” of
dereferencing and indirection.

56
Cont’d…
• A pointer to a function is simply a pointer whose
value is the address of the function name.
• Since that name is itself a pointer, a pointer to a
function is just a pointer to a constant pointer.
For example,
int f(int); // declares the function f
int (*pf) (int); // declares the function pointer pf
pf = &f; // assigns the address of f to pf

57
Cont’d…

The value of function pointers is that they allow us to


define functions of functions. This is done by passing a
function pointer as a parameter to another function.

58
Cont’d…
#include <iostream.h>
int arithmetic(int, int, int (*)(int, int));
// Take 3 arguments, 2 int's and a function pointer
// int (*)(int, int), which takes two int's and return an int
int add(int, int);
int sub(int, int);
int add(int n1, int n2) { return n1 + n2; }
int sub(int n1, int n2) { return n1 - n2; }
int arithmetic(int n1, int n2, int (*operation) (int, int)) {
return (*operation)(n1, n2);}
int main() {
int number1 = 5, number2 = 6;
// add
cout << arithmetic(number1, number2, add) << endl;
// subtract
cout << arithmetic(number1, number2, sub) << endl;
} 59

You might also like