Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the different types of functions in C Programming?
Functions in C programming are broadly classified into two types which are as follows −
- Predefined functions
- User-defined functions
Predefined (or) Library Functions
Predefined functions are already defined in the system libraries. These functions allow programmers to reuse existing code, which helps write error-free programs efficiently. The user must be aware of the syntax and header file required for each function.
- These functions are pre-written and tested by system developers
- They are available in standard library header files like
stdio.h,math.h,string.h - Programmer needs to include the appropriate header file to use them
For instance, sqrt() function is available in math.h library for calculating square root. If we use sqrt(25), it returns 5. Similarly, printf() is available in stdio.h library for output operations.
Example: Using Library Functions
#include <stdio.h>
#include <math.h>
int main() {
int x;
double y;
printf("Enter a positive number: ");
scanf("%d", &x);
y = sqrt(x);
printf("Square root = %.2f<br>", y);
return 0;
}
Enter a positive number: 25 Square root = 5.00
User-Defined Functions
User-defined functions are created by the programmer to perform specific tasks. These functions must be defined, tested, and implemented by the user according to their requirements.
- Functions are written by the programmer for specific tasks
- No need to include header files for user-defined functions
- Programmer has full control over the function's logic and implementation
- Must be properly tested before use
Examples include main(), custom calculation functions, sorting functions, etc.
Example: Creating User-Defined Function
#include <stdio.h>
int sum(int a, int b) {
int c;
c = a + b;
return c;
}
int main() {
int a, b, result;
printf("Enter 2 numbers: ");
scanf("%d %d", &a, &b);
result = sum(a, b);
printf("Sum = %d<br>", result);
return 0;
}
Enter 2 numbers: 10 20 Sum = 30
Key Differences
| Aspect | Predefined Functions | User-Defined Functions |
|---|---|---|
| Definition | Already defined in libraries | Defined by programmer |
| Header Files | Required to include | Not required |
| Testing | Pre-tested and reliable | Must be tested by programmer |
| Examples | printf(), scanf(), sqrt() | main(), custom functions |
Conclusion
Understanding both predefined and user-defined functions is essential for effective C programming. Predefined functions provide ready-to-use functionality, while user-defined functions allow customization for specific requirements.
