Functions in C++ or CPP

Functions in C++ or CPP

Functions 

A Function is a sub_program unit, used for performing a specific task. The main advantage of a function is, "define once and use many times.

Functions in C++ or CPP

A function can be defined once and that function can be invoked with different parameters many times.

For eg: A function named int GCD(int, int); can be defined once
and can be called it many times with different inputs as follows:
x = GCD(124, 356);
y = GCD(p,q);
etc.

Generally, functions are broadly categorized into 2 type:

1. Pre-defined Functions: Some functions which are already defined by the C++ compiler for performing some specific tasks.

eg: getch()  ,   sqrt(),  clrscr(), ceil( ),  floor(), tan()
When we wish to use a pre-defined function, we need to know the
signature of the function, and its header file to include to our program.

2. User-defined functions: These functions are declared, defined, and used by the users for their own purposes.

To use a function in our program we need 3 things to be taken care of:

1. Function Prototype
2. Function Definition
3. Function Call

1. Function Prototype: A function prototype specifies the name of the function, the return data type, and the parameter list.

eg: void read(int);
long int  Fact(int);
int GCD(int,int);
float si(float, float, float);

2. Function Definition: A function definition is a place where all the code is written to perform the specific task. It contains a set of statements that are to be executed when the function is invoked.

eg:     int GCD(int m, int n)
{
do{
int r = m%n;
if(r==0)
return n;
m=n;
n=r;
}while(r!=0);
}

In fucntion definition we have formal paramaters. eg: m,n are formal parameters

3. Function call: A function call is used for invoking a function, and its consists of Actual Parameters.

eg:
g = GCD(125, 45);
p = GCD(a, b);

Recursion or Recursive Functions:

If a Function is invoked within its Function Definition it is said to be Recursive Function Calling or simply Recursion.

All functions cannot be made as Recursive Functions. Only those functions which gradually reaches to some terminating point can be made as Recursive functions.

for eg: Finding Factorial of a given number

Fact(4) =
   4 X Fact(3) =
  4 x 3 x Fact(2) =
4 x 3 x 2 x Fact(1) =
Fact(n) = n x Fact(n-1) 4 x 3 x 2 x 1
Here terminating point is Fact(1) = 1 24

Every Recursive Function should have a Terminating Condition when this condition is satisfied Recursive calling of the function will be terminated.

Comments