0% found this document useful (0 votes)
10 views25 pages

Unit 2 Part 2

The document explains the concept of functions in C++, emphasizing their role in managing large programs by breaking them into smaller, manageable subprograms. It covers the structure of functions, including declaration, calling, and definition, as well as types of functions (built-in and user-defined) and parameter passing methods (by value and by reference). Additionally, it introduces function overloading, allowing multiple functions with the same name to perform different tasks based on their signatures.

Uploaded by

soham patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views25 pages

Unit 2 Part 2

The document explains the concept of functions in C++, emphasizing their role in managing large programs by breaking them into smaller, manageable subprograms. It covers the structure of functions, including declaration, calling, and definition, as well as types of functions (built-in and user-defined) and parameter passing methods (by value and by reference). Additionally, it introduces function overloading, allowing multiple functions with the same name to perform different tasks based on their signatures.

Uploaded by

soham patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Functions in C++

• functions, programs are much larger than the programs that we have seen so far. To make large
programs manageable and less complicated, they are broken down into subprograms. These
subprograms are called functions.
• The basic principle of Functions is DIVIDE AND CONQUER. Using functions, we can divide
a larger task into smaller subtasks that are manageable.
• A function is a self-contained block of statements. A function is self contained in the sense it
may have its own variables and constants.
• It is designed to do a well-defined task. Since a function is a part of a larger program (i.e. a
subprogram) it has a particular job to perform.
• It has a name. A function can be used (invoked) by the name given to it.
• It may have return type. A function invoked by a calling program may or may not return a value
to it. In case it returns a value, the functions return type is the same as the variables data type.
• A program that has functions should have the following three things in it:
• Function Declaration or Prototype
• Function Call
• Function definition
Notes prepared by Prof. Anushree K. Rewale 117
• Why use it?
• Functions are a structured way to programming. Larger programs get divided into smaller manageable units.
• If a specific block of statements has to be executed multiple times ( for example. taking contact details from 100 users), it can be
written as a function and that function can be repeatedly executed. This implies that redundancy in writing the same piece of code
multiple times is removed.
• Dividing a large program into smaller subprograms using functions help to easily code them and reduces the debugging effort.

• How does it work in an program?


• Consider the following:
int main()
{
-----------------
function1(); 1
----------------- 2
3
function2();
-----------------
4
return 0;
}
function1()
{
----------------
}

function2()
{
----------------
} Notes prepared by Prof. Anushree K. Rewale 118
• The program to the left contains three functions. First one is the main() function, second is
function1() and third is function2().
• The execution of any program begins with the execution of main function. Unless there is a
decision or looping construct the execution of the program proceeds in a serial manner.
• In the diagram to the left, the program execution begins with main(), all the statements get
executed.
• A function gets called when the function name is followed by a semicolon. A function is defined
when function name is followed by a pair of braces in which one or more statements may be
present.
• When the system encounters a call to function1() the program control jumps outside the main()
function to execute the block of statements named function1() shown by arrow number1.
• Once the last statement in function1() is executed the program control is again transferred to
main() and the immediate statement after main is executed, shown by arrow number2.
• When the system encounters a call to function2() the program control jumps outside the main()
function again to execute the block of statements named function2() shown by arrow number 3.
• Once the last statement in function2() is executed the program control is again transferred to
main() and the immediate statement after main is executed, shown by arrow number 4.
Notes prepared by Prof. Anushree K. Rewale 119
• Types of Functions:
• Functions are of two types
1. Built-in functions
2. User defined functions
• Built-in Functions:
• These are also called Standard Library Functions. As the name suggests it is a Library of functions. These are
the functions that are already present .i.e. predefined in the system.
• They have been written, compiled and placed in libraries under header files. We can use these functions in our
programs by just specifying the name of the header files that contains the function of our interest.
• Math Library Functions:
• C++ provides a library of math related functions called Math Library Functions. These functions are placed in
header file <math.h> and it contains 59 functions.
• Example : Print Square Root of Numbers from 1 to 10
#include <iostream>
#include<math>
int main()
{
cout<<“ Number "<<"\t Square Root \n";
for(int i=1;i<=10;i++)
{
cout<<i<<"\t"<<sqrt(i)<<endl;
}
return 0;
Notes prepared by Prof. Anushree K. Rewale 120
}
• User defined functions:
• These are the functions other than the Standard Library Functions. These are created by the users and the
user has the flexibility to choose the function name, the statements that will be executed, the parameters
that will be passed to the user & the return type of the function.
• Any program using functions will have the following three necessary things:
1. Function prototype or function declaration - It is the name of the function along with its return-type and
parameter list.
2. Function call - Any function name inside the main() followed by semicolon (;) is a Function Call.
3. Function Definition - A function name followed by a pair of parenthesis {} including one or more statements.
• Consider the following example:
return-type function1();
int main()
{
function1();
return 0;
}
function1()
{
----------------
return();
Notes prepared by Prof. Anushree K. Rewale 121
}
• The first line of the above example return-type function1(); is called the function prototype or
function declaration. It is used to declare the function to the compiler. This statement is always
written outside(before) the main().

• The statement function1() along with the statements in the parenthesis shown below is called the
function definition. The function definition contains the instructions to be executed when the
function is called. Function definition is always done outside the main().

• The statement function1(); inside main() is a function call. A function gets called when the function
name is followed by a semicolon. A function gets called when the function name is followed by a
semicolon.

• When this statement function1(); is executed the program control gets transferred to the function
definition of function1() which is outside the main(). All the statements inside function1() are
executed and then the control gets transferred to the next statement after the function call.
Notes prepared by Prof. Anushree K. Rewale 122
• Example:
#include <iostream>
int square(int m); // Function Prototype
int main()
{
int num, sqr=0;
cout<<"\nEnter number to find its Square"<<"\t ";
cin>>num;
sqr=square(num); // Function call
cout<<"\nSquare of "<<num<<" = " <<" = " <<sqr;
return 0;
}
int square(int x) // Function definition
{
return x*x; // returns square of x:
} Notes prepared by Prof. Anushree K. Rewale 123
• Function Definition:
• A function is defined when function name is followed by a pair of braces in
which one or more statements may be present.
• A function definition has 2 parts:
• Function head
• Function Body
• Example :
int square(int x)
{
return x*x; //returns square of x:
}
• The function returns the square of the integer passed to it. Thus the call
square(3) would return 9.
Notes prepared by Prof. Anushree K. Rewale 124
• Function Head
• The syntax for the head of a function is
return-type name(parameter-list)
• The above statement tells the compiler three things about the function:
• Name of the function.
• Its return-type i.e type of value to be returned by the function.
• Its parameter list.
• In the example shown above the head of the function is:
int square(int x)
• square is the name of the function,
• int is the type of value that the function is returning to main()
• and the parameter list (int x) contains a single parameter that is passed to the function
square by the main()
Notes prepared by Prof. Anushree K. Rewale 125
• Function Body
• The body of a function is the block of code that follows its head.
• It contains the code that performs the function’s action.
• It includes the return statement that specifies the value that the function sends back to the
place where it was called usually main().
• The body of the square function is
{
return x*x; // returns square of x:
}

Notes prepared by Prof. Anushree K. Rewale 126


• Parameter Passing to Functions
• The parameters passed to the function are called actual parameters. For example, in the
program below, 5 and 10 are actual parameters.
• The parameters received by the function are called formal parameters. For example, in the
above program x and y are formal parameters.

Notes prepared by Prof. Anushree K. Rewale 127


• There are two most popular ways to pass parameters:
• Pass by Value(Call by Value): In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are stored in different
memory locations so any changes made in the functions are not reflected in the actual parameters of
the caller.

• Pass by Reference(Call by Reference): Both actual and formal parameters refer to the same
locations, so any changes made inside the function are reflected in the actual parameters of the caller.

Notes prepared by Prof. Anushree K. Rewale 128


• Pass by Value (Call by Value)
• The examples that we have seen above are all examples of call by value. In this method of calling a
function we pass the value of variables to the function as parameters.

• Such function calls are called ‘call by value’. In call by value the changes made to the formal
parameters do not change the actual parameters.

• The called function creates a new set of variables and copies the values of actual arguments into
formal arguments.

• The function does not have access to the variables declared in the calling program and can only work
on the copies of values i.e. the formal arguments.

• Example: Consider the following program for swapping of two numbers.

Notes prepared by Prof. Anushree K. Rewale 129


#include <iostream>
void swap(int,int); //prototype
int main(void) {
int a,b;
cout << "Please enter 2 positive integers:\t ";
cin >> a>>b;
cout<<"\n Values before swapping are (in main ()):\n a = " <<a<<"\t b = "<<b<<endl;
swap(a,b); //call by value, actual arguments
cout<<"\n Values after swapping are (in main ()):\n a = " <<a<<"\t b = "<<b<<endl;
return 0;
}
void swap(int m,int n) //definition, formal arguments
{
int temp;
cout<<"\n Values before swapping are (in swap ()):\n m = " <<m<<"\t n = "<<n<<endl;
temp = m;
m = n;
n = temp;
cout<<"\n Values after swapping are(in swap ()):\n m = " <<m<<"\t n = "<<n<<endl;
} Notes prepared by Prof. Anushree K. Rewale 130
• Output:
Please enter 2 positive integers: 11 51
Values before swapping are (in main ()):
a = 11 b = 51
Values before swapping are (in swap ()):
m = 11 n = 51
Values after swapping are (in swap ()):
m = 51 n = 11
Values after swapping are (in main ()):
a = 11 b = 51

Notes prepared by Prof. Anushree K. Rewale 131


• Pass by reference (Call by reference)
• The call by value mechanism is a read only way of communication with the function and it does not change the
values of the actual arguments. It makes the functions more self-contained, protecting them against accidental
side effects.
• But sometimes there may be situations where a function may need to change the value of the parameter passed
to it. This is done by using the call by reference mechanism.
• To pass a parameter by reference instead of by value, we simply append an ampersand, &, to the data type in
the functions parameter list which the local variable a reference to the argument passed to it.
• Now the argument is read-write instead of read-only and any change to the local variable inside the function
will cause the same change to the argument that was passed to it.
• When parameters are passed by reference, the formal arguments become aliases to the actual arguments in the
calling function. This is similar to working with the same original values with two different names.
• Reference Variable – A reference variable is an alias or alternate name for a previously defined variable. Later
on the two variable names can be interchangeably used to represent the value.
Notes prepared by Prof. Anushree K. Rewale 132
• The Syntax to create a reference variable is as follows:

data-type & reference-name = variable-name;

• Example:

int a = 20;

int &b = a; //b is a reference variable

cout<<a<<endl<<cout<<b; //will both print a value of 20

a = a + 10;

cout<<b; //will print 30

• Example of swapping two numbers using pass by reference

Notes prepared by Prof. Anushree K. Rewale 133


#include <iostream>
void swap(int &,int &); //prototype
int main(void)
{
int a,b;
cout << "Please enter 2 positive integers:\t ";
cin >> a>>b;
cout<<"\n Values before swapping are (in main ()):\n a = " <<a<<"\t b = "<<b<<endl;
swap(a,b); //call by value, actual arguments
cout<<"\n Values after swapping are (in main ()):\n a = " <<a<<"\t b = "<<b<<endl;
return 0;
}
void swap(int & m,int & n) //definition, formal argument
{
int temp;
cout<<"\n Values before swapping are (in swap ()):\n m = "<<m<<"\t n = "<<n<<endl;
temp = m;
m = n;
n = temp;
cout<<"\n Values after swapping are(in swap ()):\n m = " <<m<<"\t n = "<<n<<endl;
}
Notes prepared by Prof. Anushree K. Rewale 134
• Output:
Please enter 2 positive integers: 11 51
Values before swapping are (in main ()):
a = 11 b = 51
Values before swapping are (in swap ()):
m = 11 n = 51
Values after swapping are (in swap ()):
m = 51 n = 11
Values after swapping are (in main ()):
a = 51 b = 11

Notes prepared by Prof. Anushree K. Rewale 135


• FUNCTION OVERLOADING
• Overloading means using one thing for different purposes. C++ supports function overloading.
• Function overloading is also called FUNCTION POLYMORPHISM. Under this, the same function name can
be used to create multiple function definitions to perform different tasks.
• It means that we can have a set of functions that have the same name but different signatures. A function
signature includes its return type and parameter list.
• Example: an overloaded function multiply() is shown below with possible function prototypes and associated
function calls and function definitions.
//function declarations
int multiply(int m, int n); //prototype 1
int multiply(int m, int n, int p); //prototype 2
double multiply(double m , double n); //prototype 3
double multiply(double m , int n); //prototype 4
double multiply(int m, double n); //prototype 5

//function calls
int mul = multiply(10, 20);
int mul = multiply(10, 20,3);
double mul = multiply(2.5, 3.5);
double mul = multiply(1.2, 3);
double mul = multiply(2, 3.5); Notes prepared by Prof. Anushree K. Rewale 136
//function definitions
int multiply(int m, int n)
{
return (m*n);
}
int multiply(int m, int n, int p)
{
return (m*n*p);
}
double multiply(double m , double n)
{
return (m*n);
}
double multiply(double m , int n)
{
return (m*n);
}
double multiply(int m, double n)
{
return (m*n);
}
Notes prepared by Prof. Anushree K. Rewale 137
• Example:
• Program to do arithmetic operations using function and switch case.
Function to Calculate Different Areas.
• Suppose we want to create a function to calculate the area of
different geometric figures. It makes more sense to have a function
area() which calculates different actions on different types of inputs
like :
• When given a single value, calculate the area of a square.
• For two input returns area assumes the figure is a rectangle.
• When a floating-point number is passed to the function, it calculates and returns the area
of a circle.

Notes prepared by Prof. Anushree K. Rewale 138


• INLINE FUNCTIONS
• Using functions adds to the overhead of program execution. This overhead involves time and space
to invoke the function, passing parameters, allocate memory for variables, store the values of
variables in the memory allocated, executing the instruction, returning value to the calling function,
etc.
• C++ offers the concept of inline functions to address this problem. With inline functions the
compiler replaces each call to the function with explicit code for the function .i.e. An inline function
is expanded when the function is invoked.
• A function is made inline function by simply adding the keyword inline to the function definition.
• Example
inline int square(int m)
{
return m*m;
}
• Using inline function involves a tradeoff between faster execution and memory being used. A
function with many instructions that is called multiple times gets copied every time it is executed
and occupies more memory.
Notes prepared by Prof. Anushree K. Rewale 139
• RECURSIVE FUNCTIONS
• In C++ , a recursive function is one which calls itself. It is a function being executed where one of the
instructions is to "repeat the process". It sounds similar to a loop.
• Example:
void recursive();
int main()
{
recursive();
return 0;
}
void recursive()
{
recursive();
}
• The above function will logically run in an infinite loop.
• Example : Program to find the factorial of a number
Notes prepared by Prof. Anushree K. Rewale 140
#include <iostream>
int factorial(int);
int main() {
int number,fact;
cout << "Please enter a positive integer: ";
cin >> number;
fact = factorial(number);
cout << number << " factorial is: " << fact << endl;
return 0;
}
int factorial(int number)
{
int temp;
if(number <= 1) {
return 1;
}
else {
temp = number * factorial(number - 1);
}
return temp;
}
Notes prepared by Prof. Anushree K. Rewale 141

You might also like