Friday, January 2, 2009

Functions

A function is a program which is written outside the main program. The main itself is a function. The function has its unique name. It is declared outside the main program in the beginning. Its definition is given at the beginning after its declaration or after the main program. It is called in the main program. Due to this function the program can be understood easily.
e.g.
Void add()
{
…..
}
Void main()
{

Add();
….
}
or
void add();
void main()
{
….
Add();


}
Void add()
{
….
….
}
e.g.
void hi()
{
Printf(“hi”);
}
void main()
{
Hi();
Getch();
}
The functions can be bigger than the main. In the above program the function ‘hi()’ is called. The control goes to the function, prints hi then goes to the main function then exits.
The return statement is also used in the function if a value is to be returned to the main function. Then the return type will not be void instead the data type of the returning value.
e.g.
int add(int x,int y);
void main()
{
Int x,y,z;
X=5;
Y=6;
Z=add(x,y);
Printf(“%d”,z);
Getch();
}
Int add(int x,int y)
{
Int z;
Z=x+y;
Return z;
}
In the above program the value of x and y are taken to the function added there and returned which is taken in z and printed.

No comments:

Watch tv!