0% found this document useful (0 votes)
3 views

Function in C++

The document explains the concept of functions in C++, including their purpose, types, and how to create and use them. It details two main types of functions: library functions and user-defined functions, and further categorizes user-defined functions based on their arguments and return types. Additionally, it covers function prototypes, argument passing methods, and the advantages of using functions such as code reusability and optimization.

Uploaded by

c60109771
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Function in C++

The document explains the concept of functions in C++, including their purpose, types, and how to create and use them. It details two main types of functions: library functions and user-defined functions, and further categorizes user-defined functions based on their arguments and return types. Additionally, it covers function prototypes, argument passing methods, and the advantages of using functions such as code reusability and optimization.

Uploaded by

c60109771
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Function in C++

i. A function is a group or sequence or list of statements that together perform a particular task.
ii. Every C++ program has at least one function, which is main () function.
iii. Function divides a large program into smaller program to perform a particular task.
iv. The main advantage of function is to decrease the complexity of program and remove the
repetition of code.

Types of Functions
There are two types of functions in C++ programming:

1. Library function
2. User defined function

1. Library function come along with compiler and are presented in the C++ header file such as
ceil(),pow(),strcpy(),strcmp(), scanf(), printf(), sqrt() etc.

2. User- defined functions are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the code.

 The procedure of calling both type of function is exactly same.


 There can be any number of functions in a program and any functions call any other function any
number of times.
 The order in which the function get called and the order in which they are defined in a program not
needed to be same.

Types of User-defined Functions in C++

For better understanding of arguments and return type in functions, user-defined functions can be
categorized into 4 types:

 Function with no argument and no return value


void add();

 Function with no argument but return value


int add();

1
 Function with argument but no return value
void add(int,int);

 Function with argument and return value


int add(int, int);

How to create User-defined function?

C++ Function Declaration

The syntax to declare a function is:

returnType functionName (list of parameter) ; or returnType functionName (list of parameter)


{
//body
}

Eg:
void show(); //function declaration or void show()
{
cout<<”Welcome”;
}

int main()
{

show(); //function call or calling a function

return 0;

void show() //function definition


{

//function body

Consider a situation in which you have to find the maximum of two numbers. This problem is solved by
making user-defined function in 4 different ways.

2
Example: Write a function in C++ to find the maximum of two numbers.

#include <iostream>
using namespace std;

int maxx(int,int); //function declaration


main()
{

int a,b,max;
cout<<"Enter the two numbers:";
cin>>a>>b;

max=maxx(a,b); //function call

cout<<"Maximum number:"<<max;
return 0;
}

int maxx(int x,int y) //function definition


{
if(x>y)
return x;
else
return y;
}

Function Prototype
A function prototype deceleration consists of the function name, function return type and argument list.

It tells the compiler

a) The name of the function


b) The return type of the function
c) The type and number of arguments.

When the programmer defines the function, the definition of the function must be like its prototype
deceleration. If the programmer makes a mistake, the compiler flags an error message. The function
prototype deceleration statement is always terminated with semicolon.

Example:

void max();
int max();
void max(int,int);

3
int max(int,int)

#include <iostream>
using namespace std;

int maxx(int,int); //function prototype


main()
{

int a,b,max;
cout<<"Enter the two numbers:";
cin>>a>>b;

max=maxx(a,b); //function call actual arguments

cout<<"Maximum number:"<<max;
return 0;
}

int maxx(int x,int y) //function definition formal arguments


{
if(x>y)
return x;
else
return y;
}

Function Arguments/ Passing Arguments


If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.

While calling a function, there are three ways/methods that arguments can be passed to a function –

1. Call by value(pass by value)


2. Call by address/pointer(pass by address)
3. Call by reference

4
1. Call by value-

 In call by value, value of actual argument is passes to the formal argument and operation
is done on the formal arguments. Any change in the formal argument does not affect the
actual argument because formal arguments are photocopy of the actual arguments.
 Hence, when function is called by call by value method, it does not affect the actual
contents of the actual arguments.
 Changes made in the formal argument are local to the block of called function. Once
control returns back to the calling function the change made vanish.
 By default, C++ uses call by value to pass arguments.
Example:

// function definition to swap the values.


void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into 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;
}

5
2. Call by address/pointer(pass by address)
 In call by address, instead of passing values, addresses are passed.
 Function operates on address rather than values.
 Here the formal arguments are pointers to the actual arguments.
 Hence changes made in the arguments are permanent.
Example:

// function definition to swap the values.


void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into 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;

swap(&a, &b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;

6
}

3. Call by reference

Question: What is reference variable?


Answer:

 In C++ reference type/variable, declared with “&” operator are nearly identical but not
exactly same to pointer type.
 A reference variable provides an alias for a previously defined variable i.e the same
variable’s value can be used by two different names; the original name and alias name.
 A reference variable must be initialized at the time of declaration.
 A reference variable is an alias i.e another name for an already existing
variable

Eg:
int k = 0;
int &kk=k; //kk is an alias for k
kk = 10; //any operation on kk will give the same result as operations on k.

Call by reference copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means that
changes made to the formal parameter affect the actual argument.

7
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;

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 using variable reference.*/
swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

Q: Write a member function in C++ which accepts one number as a parameter/argument and
calculate the factorial of given number.

8
Q: Write a member function in C++ which accepts one number as a parameter/argument and Check
Whether a Number is Prime or Not.

Q: Write a member function in C++ which accepts one number as a parameter/argument and
calculate the factorial of given number and return the calculated factorial to the calling function.

Q: Write a function in C++ which accepts one number as a parameter/argument and return the
reverse number of the given number to the calling function.

Q: Write a C++ program to add two numbers using call by reference.

#include<iostream>
using namespace std;
void add(int x,int y,int &z)
{
z=x+y;
}

main()
{
int a,b,s=0;
system("CLS");
cout<<"Enter the two numbers:";
cin>>a>>b;
add(a,b,s);
cout<<endl<<"sum=\t"<<s;

return 0;

Return reference to calling function

#include<iostream>
using namespace std;
int &add(int x,int y)
{
int z=x+y;
int &r=z;
return r;
}

main()
{
int a,b,s=0;
system("CLS");

9
cout<<"Enter the two numbers:";
cin>>a>>b;
s=add(a,b);
cout<<endl<<"sum=\t"<<s;

return 0;

Passing Array to a Function in C++

If you want to pass array as a parameter to the function than function deceleration specify the
data type of array and empty square bracket([]) and when you call the function than just pass
the name of the array.

Let's see the simple example to get the maximum number of an array using a function.
#include <iostream>
using namespace std;
void find_max(int no,int x[])
{
int i,max=0;

for(i=0;i<no;i++)
{
if(x[i]>max)
max=x[i];
}
cout<<"Max:\t"<<max;
}

main()
{

int i,no,a[10],max;

cout<<"Enter the size of array:";


cin>>no;
cout<<"Enter the array elements one by one:";
for(i=0;i<no;i++)
{
cin>>a[i];
}

find_max(no, a);

return 0;
}

Q: create a function in C++ that takes/accept two parameters/argument: an integer array and
array size; return the smallest value to calling function.

10
Advantage of functions in C++

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the same code again
and again.

2) Code optimization

It makes the code optimized; we don't need to write much code.

Example:

Suppose, you have to check 3 numbers (112, 553 and 21) whether it is prime number or not. Without
using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.

11

You might also like