A function is a block of statement that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.
A function is a self contained block of statements that perform a coherent task of the same kindFunction helps to groups a number of program statements into a unit and gives it a name. This unit can be invoked from the other parts of a program.It is not possible by computer program to handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done.
In a C Program,the name of the function is unique and is Global. It meams that a function can be accessed from any location with in a C Program.when the function is called,we pass information to the function called arguments specified.And the function either returns some values to the point it was called from or returns nothing
--------------------------------------------------------------------------------
Structure of a Function
There are two main parts of the functions. The function header and the function body.
--------------------------------------------------------------------------------
The following syntax shows th syntax of using function in c:
return_ data_type function name (arguments, arguments)
data _type _declarations of arguments;
{
function body
}
--------------------------------------------------------------------------------
Function Header
int sum(int x, int y)
It has three main parts
The function name i.e. sum
The parameters of the function enclosed in the paranthesis
Return value type of the function i.e. int
--------------------------------------------------------------------------------
Function Body
What ever is written with in { } is the body of the function.
The following example shows the use of functions which prints factorial of a number:
* Program to calculate a specific factorial number */
#iinclude
void calc_factorial (int); // ANSI function prototype
void calc_factorial (int i)
{
int I, factorial_number = 1;
for (I=1; I <=n; ++i)
factorial_number *= I;
printf("The factorial of %d is %d\n", n, factorial_number);
}
int main(void)
{
int number = 0;
printf("Enter a number\n");
scanf("%d", &number);
calc_factorial (number);
return 0;
}