πΉ What is a Function in C?
A function is a block of code that performs a specific task. In C, functions help to:
- Break down complex programs into smaller, manageable parts.
- Reuse code by calling the same function multiple times.
- Improve readability and maintainability.
πΉ Types of Functions in C
- Library Functions
- Built-in functions provided by C (e.g.,
printf()
,scanf()
,sqrt()
) - Defined in header files like
stdio.h
,math.h
, etc.
- User-defined Functions
- Created by the programmer to perform specific tasks.
πΉ Syntax of a User-defined Function
return_type function_name(parameter_list) {
// body of the function
}
Example:
int add(int a, int b) {
return a + b;
}
πΉ Components of a Function
Component | Description |
---|---|
Return type | Type of value returned (e.g., int, void) |
Function name | Identifier name of the function |
Parameters | Input values (optional) |
Function body | Code block performing specific operations |
Return statement | Sends result back to caller (optional) |
πΉ Function Declaration / Prototype
Before using a function, you must declare it (unless defined before the main function).
int add(int, int); // Function prototype
πΉ Function Call
To execute a function, you need to call it using its name and pass arguments:
int result = add(5, 3);
πΉ Complete Example
Letβs see a complete C program using a user-defined function:
#include <stdio.h>
// Function declaration
int add(int, int);
// Main function
int main() {
int x = 10, y = 20, sum;
sum = add(x, y); // Function call
printf("Sum = %d\n", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
π‘ Output:
Sum = 30
πΉ Categories of Functions Based on Arguments and Return Value
Type | Description & Example |
---|---|
1. No arguments, no return value | void greet(); |
2. Arguments, no return value | void display(int); |
3. No arguments, return value | int getValue(); |
4. Arguments and return value | int multiply(int, int); |
πΉ Example: No Arguments, No Return Value
#include <stdio.h>
void greet() {
printf("Hello! Welcome to C programming.\n");
}
int main() {
greet();
return 0;
}
πΉ Why Use Functions?
- Modularity β Breaks large programs into smaller chunks.
- Reusability β Same function can be used multiple times.
- Easier testing β Each function can be tested independently.
- Better organization β Code is cleaner and more readable.
If you want, I can also explain recursive functions, inline functions, or help you write functions for specific tasks like factorial, prime check, file handling, etc.