SlideShare a Scribd company logo
1 of 63
CHAPTER THREE
FUNCTION
For second year IT regular student
Information Technology depā€™t
Compiled by BAYISA NATEA Nov 27, 2014 1
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.
Otherwise the program will not compile.
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
variables represented by the function parameters.
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;
}
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;
}
int show(int x, int y)
{
int z;
z=x * y;
return z;
}
The variable a , b are known as
actual parameters whose
values are copied to the
dummy variables x and y. The
result of the multiplication is
stored in z and this value is
copied to c. 27
Returning values by references
A function can also return by reference.
28
Contā€™dā€¦
#include<iostream.h>
#include<iomanip.h>
int & check(int & a,int &b)
{
if(a>b)
return a;
else
return b;
}
void main( )
{
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;
}
This function returns reference to a
or b. The function check returns
reference to either x or y based on
the condition. Thus whatever value
is given as input for x and y the
function call assigns the value of x
to the reference that is returned
thus the cout statement displays
the value of x twice.
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.
inline function-prototype
{
function body
}
When the function is defined
Inline, the C++ compiler puts the
function body inside the calling
function. You can define function as
Inline when the function body is
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;
y = x * x;
return y;
}
int main()
{
int a =3, b;
b = sqr(a);
cout <<b;
return 0;
}
Here, the statement b = sqr(a) is a
function call to sqr(). But since we have
declared it as inline, the compiler
replaces the statement with the
executable stmt of the function (b = a
*a)
Please note that, inline is a request to
the compiler. If it is very complicated
function, compiler may not be able to
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>
// Function prototype with default arguments
void displayStars(int = 10, int = 1);
int main(){
displayStars(); // Use default values for cols and rows.
cout << endl;
displayStars(5); // Use default value for rows.
cout << endl;
displayStars(7, 3); // Use 7 for cols and 3 for rows.
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;
} }
#include <iostream.h>
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main ()
{
cout << divide (12) << 'n';
cout << divide (20,4) << 'n';
return 0;
}
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>
#include<iomanip.h>
void sum(int,int);
void sum(int,int,int);
void main()
{
int a ,b, c ;
cout<<ā€Enter three values
ā€œ<<endl;
cin>>a>>b>>c;
cout<<ā€Calling the function
with two parametersā€<<endl;
sum(a,b);
Cout<<ā€Calling the function
with three
parametersā€<<endl;
sum(a,b,c);
}
void sum(int x,int y)
{
int z;
z=x+y;
cout<<z;
}
void sum(int x,int y,int z)
{
int r;
r=x+y+z;
cout<<r;
}
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";
return 0; }
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>
int factorial(int);
int main()
{
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = ā€œ
<<factorial(n);
return 0;
}
int factorial(int n) { if (n>1)
{
return n*factorial(n-1); }
else
{
return 1;
} }
# include <iostream.h>
int Fibonacci(int n)
/* Fibonacci: recursive version */
{
if(n<=0) return 0;
else if(n==1) return 1;
else
{
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
int main()
{
int a;
cin>>a;
cout<<Fibonacci(a);
}
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
The stack and the heap
ā€¢ The stack is where local variables and function
parameters reside. It is called a stack because it
follows the last-in, first-out principle.
ā€¢ As data is added or pushed to the stack, it grows,
and when data is removed or popped it shrinks.
ā€¢ When a function or a method calls another function
which in turns calls another function etc., the
execution of all those functions remains suspended
until the very last function returns its value.
ā€¢ The stack has a limited size, and consequently can
only hold a limited amount of information. If the
program tries to put too much information on the
stack, stack overflow will result
60
Contā€™dā€¦
ā€¢ When a C++ program starts, 5 distinct areas of memory
are created. These are:
1. Code Space: This is where the executable instructions
of the program are kept.
2. Registers: are part of the CPU that take care of internal
housekeeping. Among other things, they contain an
identifier that points to the next line of code that is to
be executed, and the stack pointer.
3. Global Name Space: contains objects allocated by the
linker which will persist for the duration of the
program.
4. Stack: contains local variables, whose persistency is
defined by their scope.
5. Free Store, or Heap is explicitly created and destroyed
by issuing new and delete commands. 61
Contā€™dā€¦
ā€¢ The heap (also known as the ā€œfree storeā€) is a large
collection of memory used for dynamic allocation. In
C++, when you use the new operator to allocate
memory, this memory is assigned from the heap.
int *pValue = new int; // pValue is assigned 4 bytes from
the heap
int *pArray = new int[10]; // pArray is assigned 40 bytes
from the heap.
ā€¢ Because the heap is a big pool of memory, large arrays,
structures, or classes should be allocated here.
ā€¢ Memory space for objects is always allocated in heap.
Objects are placed on the heap.
ā€¢ Built-in datatypes like int, double, float and parameters
to function are allocated on the stack. 62
I THANK YOU!!
63

More Related Content

Similar to IT Functions Chapter 3

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
Ā 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2sumitbardhan
Ā 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
Ā 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in CRAJ KUMAR
Ā 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
Ā 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxsarthakgithub
Ā 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
Ā 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 FunctionsSzeChingChen
Ā 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdfNirmalaShinde3
Ā 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxSKUP1
Ā 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxLECO9
Ā 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptxMehul Desai
Ā 

Similar to IT Functions Chapter 3 (20)

arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Ā 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ā 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
Ā 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
Ā 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
Ā 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
Ā 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Ā 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Ā 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
Ā 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Ā 
Function
Function Function
Function
Ā 
Functions
Functions Functions
Functions
Ā 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Ā 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
Ā 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
Ā 
4th unit full
4th unit full4th unit full
4th unit full
Ā 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Ā 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
Ā 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
Ā 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
Ā 

Recently uploaded

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
Ā 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
Ā 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
Ā 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
Ā 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
Ā 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
Ā 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
Ā 
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...Nguyen Thanh Tu Collection
Ā 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
Ā 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
Ā 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
Ā 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
Ā 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
Ā 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
Ā 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
Ā 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
Ā 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
Ā 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
Ā 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Ā 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
Ā 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
Ā 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
Ā 
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...
Hį»ŒC Tį»T TIįŗ¾NG ANH 11 THEO CHĘÆĘ NG TRƌNH GLOBAL SUCCESS ĐƁP ƁN CHI TIįŗ¾T - Cįŗ¢ NĂ...
Ā 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
Ā 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
Ā 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
Ā 

IT Functions Chapter 3

  • 1. CHAPTER THREE FUNCTION For second year IT regular student Information Technology depā€™t Compiled by BAYISA NATEA Nov 27, 2014 1
  • 2. 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
  • 4. 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
  • 5. 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
  • 6. Structure of a function 6
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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. Otherwise the program will not compile. 11
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 17. 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
  • 19. 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
  • 20. 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 variables represented by the function parameters. 20
  • 21. 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; } 21
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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; } int show(int x, int y) { int z; z=x * y; return z; } The variable a , b are known as actual parameters whose values are copied to the dummy variables x and y. The result of the multiplication is stored in z and this value is copied to c. 27
  • 28. Returning values by references A function can also return by reference. 28
  • 29. Contā€™dā€¦ #include<iostream.h> #include<iomanip.h> int & check(int & a,int &b) { if(a>b) return a; else return b; } void main( ) { 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; } This function returns reference to a or b. The function check returns reference to either x or y based on the condition. Thus whatever value is given as input for x and y the function call assigns the value of x to the reference that is returned thus the cout statement displays the value of x twice. 29
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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. inline function-prototype { function body } When the function is defined Inline, the C++ compiler puts the function body inside the calling function. You can define function as Inline when the function body is 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
  • 35. 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
  • 36. 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
  • 37. 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; y = x * x; return y; } int main() { int a =3, b; b = sqr(a); cout <<b; return 0; } Here, the statement b = sqr(a) is a function call to sqr(). But since we have declared it as inline, the compiler replaces the statement with the executable stmt of the function (b = a *a) Please note that, inline is a request to the compiler. If it is very complicated function, compiler may not be able to convert it to inline 37
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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
  • 42. Contā€™dā€¦ // This program demonstrates default function arguments. #include <iostream.h> // Function prototype with default arguments void displayStars(int = 10, int = 1); int main(){ displayStars(); // Use default values for cols and rows. cout << endl; displayStars(5); // Use default value for rows. cout << endl; displayStars(7, 3); // Use 7 for cols and 3 for rows. 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; } } #include <iostream.h> int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12) << 'n'; cout << divide (20,4) << 'n'; return 0; } 42
  • 43. 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
  • 44. 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
  • 45. Contā€™dā€¦ #include<iostream.h> #include<iomanip.h> void sum(int,int); void sum(int,int,int); void main() { int a ,b, c ; cout<<ā€Enter three values ā€œ<<endl; cin>>a>>b>>c; cout<<ā€Calling the function with two parametersā€<<endl; sum(a,b); Cout<<ā€Calling the function with three parametersā€<<endl; sum(a,b,c); } void sum(int x,int y) { int z; z=x+y; cout<<z; } void sum(int x,int y,int z) { int r; r=x+y+z; cout<<r; } 45
  • 46. 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"; return 0; } 46
  • 47. 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
  • 49. 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
  • 50. Contā€™dā€¦ #include <iostream> int factorial(int); int main() { int n; cout<<"Enter a number to find factorial: "; cin>>n; cout<<"Factorial of "<<n<<" = ā€œ <<factorial(n); return 0; } int factorial(int n) { if (n>1) { return n*factorial(n-1); } else { return 1; } } # include <iostream.h> int Fibonacci(int n) /* Fibonacci: recursive version */ { if(n<=0) return 0; else if(n==1) return 1; else { return Fibonacci(n-1)+Fibonacci(n-2); } } int main() { int a; cin>>a; cout<<Fibonacci(a); } 50
  • 51. 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
  • 52. 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
  • 53. 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
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. The stack and the heap ā€¢ The stack is where local variables and function parameters reside. It is called a stack because it follows the last-in, first-out principle. ā€¢ As data is added or pushed to the stack, it grows, and when data is removed or popped it shrinks. ā€¢ When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. ā€¢ The stack has a limited size, and consequently can only hold a limited amount of information. If the program tries to put too much information on the stack, stack overflow will result 60
  • 61. Contā€™dā€¦ ā€¢ When a C++ program starts, 5 distinct areas of memory are created. These are: 1. Code Space: This is where the executable instructions of the program are kept. 2. Registers: are part of the CPU that take care of internal housekeeping. Among other things, they contain an identifier that points to the next line of code that is to be executed, and the stack pointer. 3. Global Name Space: contains objects allocated by the linker which will persist for the duration of the program. 4. Stack: contains local variables, whose persistency is defined by their scope. 5. Free Store, or Heap is explicitly created and destroyed by issuing new and delete commands. 61
  • 62. Contā€™dā€¦ ā€¢ The heap (also known as the ā€œfree storeā€) is a large collection of memory used for dynamic allocation. In C++, when you use the new operator to allocate memory, this memory is assigned from the heap. int *pValue = new int; // pValue is assigned 4 bytes from the heap int *pArray = new int[10]; // pArray is assigned 40 bytes from the heap. ā€¢ Because the heap is a big pool of memory, large arrays, structures, or classes should be allocated here. ā€¢ Memory space for objects is always allocated in heap. Objects are placed on the heap. ā€¢ Built-in datatypes like int, double, float and parameters to function are allocated on the stack. 62