Functions
Functions
⚫ Function
Declaration
⚫ Function Call
⚫ Function Definition
Form of Function
Syntax: Function Declaration
return_type function_name(parameter list) ;
Syntax : Function Call
int main()
{ Function_name(parameter list);
}
Syntax: Function Definition
{
______
__ ____
}
FunctionDeclaration
⚫ A function declaration is made by declaring the
return type of the function, name of the function and
the data types of the parameters of the function.
⚫ Always terminated by semicolon.
⚫ The general form of function declaration :-
return_type function_name(parameter list);
⚫ The return_type specifies the type of the
data the function returns.
⚫ The parameter list could be empty .
⚫ The parameter list should contain both
data type and name of the variable.
⚫ For example,
int factorial(int n, float j)
Function Arguments
⚫ Arguments contain the actual value which is to be
passed to the function when it is called.
⚫ The sequence of the arguments in the call of the
function should be same as the sequence of the
parameters in the parameter list of the
declaration of the function.
⚫ When a function call is made arguments
replace the parameters of the function.
The Return Statement and Return values
}
Pass/Call by value
⚫ Copies of the arguments are created .
⚫ The parameters are mapped to the copies of the
arguments created.
⚫ The changes made to the parameter do not affect the
arguments.
Example
#include<iostream.h
> #include<conio.h>
int add(int n);
int main()
{
int
number,result;
number=5;
cout << " The initial value of number : " << number <<
endl;
result=add(number);
cout << " The final value of number : " << number << endl;
cout << " The result is : " << result << endl;
getch();
return(0);
}
{
sum = sum*(1+r);
year = year+1;
}
getch();
return(sum);
}
void printline(char ch, int len)
{
for(int
i=1;i<=len;i++)
printf("%ch",ch);
printf("\n");
}
Function Overloading
⚫ A function is overloaded when same name is
given to different function.
⚫ The two functions with the same name
will differ at least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance
Example
#include <iostream.h>
#include<conio.h>
class arithmetic {
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}
void calc(int num1, int num2 )
{
cout<<"Product of two whole numbers: "
<<num1*num2 <<endl;
}
};
int main() //begin of main
function
{
arithmetic
a; a.calc(4);
a.calc(6,7);