UNIT-4
FUNCTIONS, ARRAYS AND
STRING HANDLING
FACULTY NAME: Er. Kamaldeep Kaur
CHAPTER CONTENTS
FUNCTION COMPONENTS
DEFAULT ARGUMENTS
PASSING PARAMETERS
FUNCTION PROTOTYPING
CALL BY VALUE, CALL BY REFERENCE, RETURN BY REFERENCE
INLINE FUNCTIONS
FRIEND FUNCTIONS
STATIC FUNCTIONS
RECURSION
ARRAY DECLARATION, TYPES OF ARRAYS
ARRAY OF OBJECTS
STRING HANDLING.
FUNCTION
A function groups a number of program statements
into a unit and gives it a name.
ADVANTAGES
A program may need to repeat the same piece of code at
various places i.e. reusability of code.
It may be required to perform certain task repeatedly.
The program may become very large if functions are not used.
The real reason for using function is to divide program into
different parts.
Easier to maintain and understand the program.
FUNCTION COMPONENTS
Function declaration: Function declaration is the model
of a function. It is also known as FUNCTION
PROTOTYPE. It provides information to compiler
about the structure of function to be used in program
Function call: The statement that activates a function is
known as FUNCTION CALL
Function definition: A set of statements that explains
what a function does is called FUNCTION Definition
FUNCTION DECLARATION
It ends with semicolon (;). It consists of:
• FUNCTION NAME
• FUNCTION RETURN TYPE
• NUMBER & TYPES OF PARAMETERS
FUNCTION DECLARATION SYNTAX
FUNCTION DEFINITION SYNTAX
FUNCTION CALL
The following steps take place when a function is
called:
1.The control moves to the function that is
called.
2. All statements in function body are executed.
3. Control returns back to calling function.
FUNCTION CALL
EXAMPLE
CALL BY VALUE vs CALL BY REFERENCE
CALL BY VALUE
#include<iostream>
using namespace std;
void swap(int,int);
int main()
{
int a,b;
cout<<"\n Enter First Number : ";
cin>>a;
cout<<"\n Enter Second Number : ";
cin>>b;
cout<<"\n Before Swapping the Value : \n"<<" "<<a<<"\t"<<b<<"\n";
swap(a,b);
}
void swap(int x,int y)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"\n After Swapping the Value : \n"<<" "<<a<<"\t"<<b;
}
CALL BY REFERENCE
#include<iostream>
using namespace std;
void swap (int &num1, int &num2) //&num1 and &bnum2 are Reference variables
{
int temp;
temp=num1;
num1=num2;
num2=temp;
}
int main()
{
int a=5,b=10;
cout<<"\n Before swapping"<<"\n A = "<<a<<"\n B = "<<b<<endl;
swap(a,b);
cout<<"\n After swapping"<<"\n A = "<<a<<"\n B = "<<b<<endl;
return 0;
}
CALL BY POINTER
#include <iostream>
using namespace std;
void swap(int*, int*);
int main() {
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function by passing variable addresses swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
// function definition to swap numbers
void swap(int* n1, int* n2)
{ int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp; }
RETURN BY REFERENCE
A function can also return a reference.
int &max(int &x,int &y)
{ if(x>y) return x;
else return y;
}
Since the return type of max() is int&, the function returns
reference to x or y. Then a function call such as max(a,b) will
yield a reference to either a or b, depending on their values.
The statement max(a,b)=-1; is legal and assigns -1 to a if it is
larger, otherwise -1 to b.
DEFAULT ARGUMENTS
A function can be called even without specifying all its
arguments.
In such cases, the function assigns a default value to the
parameter which does not have a matching argument in the
function call.
Default values are specified when the function is declared.
EXAMPLE:
float amount(float principal, int period, float rate=0.15);
The above prototype declares a default value of 0.15 to rate. A subsequent
function call
Value=amount(5000,7); //passes the value 5000 to principal and 7 to period and
lets the function use default value of 0.15 for rate.
The call value=amount(5000,5,0.12); passes an explicit value of 0.12 to rate
DEFAULT ARGUMENTS
** only the trailing arguments can have default
values and therefore they can be added from right
to left.
EXAMPLES:
int mul(int I, int j=5, int k=10); //legal
int mul(int i=5, int j); //illegal
int mul(int i=0, int j, int k=10); //illegal
int mul(int i=2, int j=5, int k=10); //legal
DEFAULT ARGUMENTS
#include<iostream> float value(float p, float t, float r)
using namespace std; {
int main() float SI;
{ SI=(p*t*r)/100;
float interest; return SI;
float value( float p, float t, float r=0.15); }
void printline(char ch=‘*’, int len=40); void printline(char ch, int len)
printline(); {
interest=value(5000.00,5); for(int i=1; i<=len;i++)
cout<<“\nfinal value=“<<interest<<“\n”; cout<<ch;
printline(‘=‘); cout<<“\n”;
return 0; }
} Output: ******************
37.50
FUNCTION OVERLOADING
Overloading refers to the use of the same thing for
different purposes.
The same function name can be used to create
functions that perform a variety of different tasks.
The functions are differentiated on the basis of
number and type of arguments.
FUNCTION OVERLOADING
EXAMPLES:
//DECLARATIONS
int add(int a, int b); //1
int add(int a, int b, int c); //2
double add(double x, double y); //3
double add(int p, double q); //4
double add(double p, int q); //5
//FUNCTION CALLS
add(5,10); // 1
add(15,10.0); //4
add(12.5,7.5); //3
add(5,10,15); //2
add(0.75,5); //5
FUNCTION OVERLOADING
INLINE FUNCTION
C++ provides an inline function to reduce the function call
overhead.
Inline function is a function that is expanded in line when it is
called.
When the inline function is called whole code of the inline
function gets inserted or substituted at the point of inline
function call.
This substitution is performed by the C++ compiler at compile
time.
Inline function may increase efficiency if it is small.
PURPOSE OF INLINE FUNCTION
When the program executes the function call instruction, the CPU stores the
memory address of the instruction following the function call, copies the
arguments of the function on the stack and finally transfers control to the
specified function.
The CPU then executes the function code, stores the function return value in
a predefined memory location/register and returns control to the calling
function.
This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of
the function call is usually insignificant compared to the amount of time the
function takes to run.
However, for small, commonly-used functions, the time needed to make the
function call is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because execution
time of small function is less than the switching time.
ADVANTAGES OF INLINE FUNCTION
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables
on the stack when function is called.
3) It also saves overhead of a return call from a
function
INLINE FUNCTION
All the functions defined inside the class are implicitly inline.
The function defined outside the class can also be made inline
by using the keyword ‘inline’ before the function definition.
SYNTAX:
inline return-type function-name(parameters)
{ // function code }
FRIEND FUNCTION
A friend function is an outside function that can be
made friend to a class.
The function declaration should be preceded by the
keyword ‘friend’.
The function definition does not use the keyword
friend or the scope resolution operator.
The friend function can access the private members of
the class.
PROPERTIES OF FRIEND FUNCTION
It is not in the scope of the class to which it has been declared
as friend.
It cannot be called using the object of that class.
It can be invoked like a normal function.
Unlike member functions, it cannot access the member names
directly and has to use an object name and dot membership
operator with each member name.
It can be declared either in the public or the private part of a
class, without affecting its meaning.
Usually, it has the objects as arguments.
FRIEND FUNCTION
#include<iostream> int main()
using namespace std; {
class sample sample x;
{ int a,b; //private // x.setvalue();
public: cout<<“mean
value=“<<mean(x); //call
sample() {a=25;b=40;}
return 0;
// void setvalue() {a=25; b=40;}
}
friend float mean(sample s);
//declaration
};
float mean(sample s) //definition
{
return float (s.a+s.b)/2.0;
}
FRIEND CLASS
#include<iostream> friend void max(XYZ,ABC);
using namespace std; };
class ABC; //forward declaration void max(XYZ m, ABC n)
class XYZ {
{ if(m.x>=n.a)
int x; cout<<m.x;
public: else
void setvalue(int i) cout<<n.a;
{ x=i;} }
friend void max(XYZ,ABC); int main()
}; {
class ABC ABC abc;
{ abc.setvalue(10);
int a; XYZ xyz;
public: xyz.setvalue(20);
void setvalue(int i) max(xyz,abc);
{ a=i;} return 0;
}
STATIC MEMBER FUNCTIONS
It can have access to only other static members (functions or
variables) declared in the same class.
It can be called using the class name (instead of its objects) as
follows:
class-name :: function-name;
STATIC MEMBER FUNCTIONS
#include<iostream> int test :: count;
using namespace std; int main()
class test {
{ test t1,t2;
static int count; t1.setcode();//count=1, code=1
int code=0; t2.setcode();//count=2,code=1
public: test:: showcount();//2
void setcode() test t3;
{ t3.setcode();//count=3,code=1
code=++count; test:: showcount();//3
} return 0;
static void showcount() }
{
cout<<“count:”<<count<<“\n”;
// cout<<code; //error, code is not
//static
}
};
RECURSION
A function that calls itself is known as a recursive
function. And, this technique is known as recursion.
FACTORIAL OF A NUMBER USING RECURSION
#include <iostream> int factorial(int n)
using namespace std; { if (n > 1)
int factorial(int); { return n * factorial(n - 1);
int main() }
{ int n, result; else
cout << "Enter a non-negative { return 1; }
number: "; }
cin >> n;
result = factorial(n); OUTPUT:
cout << "Factorial of " << n << Enter a non-negative number: 4
" = " << result;
Factorial of 4 = 24
return 0;
}
ADVANTAGES OF C++ RECURSION
It makes our code shorter and cleaner.
Recursion is required in problems concerning data
structures and advanced algorithms, such as Graph
and Tree Traversal.
DISADVANTAGES OF C++ RECURSION
It takes a lot of stack space compared to an
iterative program.
It uses more processor time.
It can be more difficult to debug compared to an
equivalent iterative program.
ARRAY
ARRAY OF OBJECTS
class student
{ int roll_no, int marks; //int a,b,c,d,e; int a[5];
public: for(int i=1;i<=5;i++)
void getdata() { cin>>a[5];}
{cin>>roll_no>>marks;}
void display()
{cout<<roll_no<<marks;}
};
int main()
{ student s1,s2,s3,s4,s5; student s[5];
for(int i=1;i<=5;i++)
{ s[i].getdata();
}
STRING HANDLING