Functions in c++
Functions in c++
1
Function
A function is a block of code that performs a
specific task.
Example: Suppose we need to create a program
to create a circle and color it. We can create two
functions to solve this problem:
•a function to draw the circle
•a function to color the circle
2
Types
multiply()
{
;
}
Parts of a function
main function
{
function prototype declaration
function call
-------;
}
function declaratory/definition
{
------;
return statement
}
Function prototype
A function prototype is a declaration of a function that tells the
program about the type of value returned by the function, name of
function, number and type of arguments.
Syntax:
Return_type function_name (parameter list/argument);
int add(int,int);
void add(void);
int add(float,int);
4 parts
i. Return type Variable declaration
ii. Function name Data_type variable_name ;
int x=5;
iii. Argument list float marks; int price;
iv. Terminating
semicolon
Function call
A function must be called by its name followed by
argument list enclosed in semicolon.
add(x,y);
add(40,60);
add(void); or add();
Note: data type not to be mentioned.
void sqr()
{
int no;
cout<<“enter a no.”; cin>>no;
cout<<“square of”<<no<<“is”<<no*no;
}
ii. Function will not return any value but passes argument
#include<iostream.h>
#include<conio.h>
void add(int,int);
int main()
{
int a,b;
add(a,b);
cout<<“enter values of a and b”<<endl;
cin>>a>>b; a
add(a,b);
getch(); return 0;
} b
void add(int x,int y)
{
int c; c=x+y; void
cout<<“addition is”<<c; add(int
}
x,int y);
iii) Function with arguments and return value
main function
{
int sqr(int); //function prototype
int a,ans;
cout<<“enter a number”; cin>>a;
ans=sqr(&a);
cout<<“square of number is”<<ans; //function call
getch();
return 0;
}
int add(void);
{
int a,b;
cout<<“enter 2 nos”;
cin>>a>>b;
return(a+b);
}
Call by value
A function can be invoked in two manners (i)call by value
(ii)call by reference
The call by value method copies the value of actual parameters into
formal parameters i.e the function creates its own copy of
arguments and uses them.
Call by value
} X,Y
where the values of void add(int x,int y); Now if you change
variable are passed
to functions { the value of X and Y,
those changes are
--------; not seen in a and b
}
Call by
reference
In call by reference method in place of calling a value to the function being
called , a reference to the original variable is passed .i.e the same variable
value can be accessed by any of the two names.
In function call
add(a,b); We write reference
variable for formal
} arguments
dataType arrayName[arraySize];
int x[6]; int y[10] ={1,2,3,4,5,6,..10}
18
• X={20,10,40,50}
• X[0]=20
• X[1]=10
• X[2]=40
• X[3]=50
• X[2][3]=
• X[3][3]
19