C function is a self-contained block of statements that can be executed repeatedly whenever we need it.
Benefits of using the function in C
- The function provides modularity.
- The function offers reusable code.
- In large programs, debugging and editing tasks are effortless with functions.
- The program can be modularized into smaller parts.
- A separate function can be developed independently according to the need.
There are two types of functions in C
- Built-in(Library)
Functions
- The system provided these functions and stored them in the
library. Therefore it is also called Library Functions.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc. - You need to include the appropriate C header files to use these functions.
- The system provided these functions and stored them in the
library. Therefore it is also called Library Functions.
- User Defined Functions These functions are defined by the user when writing the program.
Parts of Function
- Function Prototype (function declaration)
- Function Definition
- Function Call
1. Function Prototype
Syntax:
dataType functionName (Parameter List)
Example:
int addition();
2. Function Definition
Syntax:
returnType functionName(Function arguments){
//body of the function
}
Example:
int addition()
{
}
3. Calling a function in C
Program to illustrate the Addition of Two Numbers using User Defined Function
Example:
#include<stdio.h>
/* function declaration */
int addition();
int main()
{
//local variable definition
int answer;
answer = addition(); //calling a function to get addition value.
printf("The addition of the two numbers is: %d\n",answer);
return 0;
}
//function returning the addition of two numbers
int addition()
{
int num1 = 10, num2 = 5; // local variable definition
return num1+num2;
}
Program Output:
The addition of the two numbers is: 15