Functions in C
Function is small set of program which is created to do certain task.
Any function in C has a parenthesis in front of it.
Their are 2 types of functions:
- In-build functions
- User defined functions
In-build functions are those which are already pre-written in C header files.
We just have to include header files to use these functions.
e.g of in-build functions are: printf(), scanf(), strlen(), strcat(), etc.
But, C also provides user an option to user to declare functions.
Syntax for declaring function is:
return_type function_name (argument_list)
{
...
...
}
Any function in C has 3 parts namely:
- Function declaration.
- Function call.
- Function definition.
Let's see small example:
#include<stdio.h>
int add(int,int); //Function declaration//
void sub(int,int); //Function declaration//
void main()
{
int a,b,c;
printf("Enter numbers to be added and
subtracted:");
scanf("%d%d",&a,&b);
c=add(a,b); //Function call//
printf("\nAddition is: %d",c);
sub(a,b); //Function call//
}
int add(int a,int b) //Function definition//
{
return(a+b);
}
void sub(int a,int b) //Function definition//
{
printf("\nSubtraction is:
%d",a-b);
}
Output:
We can declare such n number of functions.
We can or cannot have something to return from function depending on that we keep our function's return type as void or int or float or any other data type.
Why to use functions?:
- We can call function n number of times.
- Also, size of void main is reduced.
- It becomes easy to decode and find out our mistakes (errors).
A function which calls itself is called as recursive function.
See program for recursive function for better understanding.
No comments:
Post a Comment