What is a Function
A function is a block of statements that perform a some task. Every C program can be thought of as a collection of these functions. Using a function is something like hiring a person to do a specific job for you.
consider a C program where in you have several tasks writing everything inside main() is not worth it.instead we should modularise it and then proceed.
see the example below
[c]void display(); // Declaring the function
void main()
{
display(); // Calling a function
}
void display() // Defining the function
{
printf("\nFirst Line");
printf("\nSecond Line");
}[/c]
Above simple program tells us three things about function.
1.Declaring the function
2.Defining the function
3.Calling a function
Below is the prototype of a function
return_type function_name(arguments)
A function may have one or more arguments or no arguments.
Addition of two numbers using function
[c]void add(int a,int b)
{
int c;
c=a+b;
printf("\nThe addition is %d",c);
}
void main()
{
int x,y;
printf("\nEnter x and y ");
scanf("%d%d",&x,&b);
add(x,y);
getch();
}[/c]
Addition of two numbers using function returning a value
[c]int add(int a,int b)
{
return(a+b);
}
void main()
{
int x,y,ans;
printf("\nEnter x and y ");
scanf("%d%d",&x,&b);
ans=add(x,y);
printf("Addition of %d and %d is : ",x,y,ans);
getch();
}[/c]