Functions in C Programming
Definition:
A function in C is a self-contained block of code that performs a specific task.
It can be called multiple times to perform the same operation without rewriting the code.
Types of Functions:
1. Library Functions:
- Predefined in C standard library.
- Examples: printf(), scanf(), strlen(), sqrt()
2. User-defined Functions:
- Created by the programmer to perform custom tasks.
- Can be reused throughout the program.
Benefits of Using Functions:
- Modularity: Large programs can be broken into smaller parts.
- Reusability: A function can be used multiple times.
- Code readability: Easier to read and understand.
- Ease of debugging: Isolated testing and fixing.
- Abstraction: Users can use a function without knowing its internal details.
Function Components:
1. Function Declaration (Prototype):
int add(int, int);
2. Function Definition:
int add(int a, int b) {
return a + b;
3. Function Call:
int result = add(5, 3);
Syntax:
return_type function_name(parameter1, parameter2, ...) {
// Function body
return value; // if return_type is not void
Example Program:
#include <stdio.h>
int multiply(int, int);
int main() {
int x = 4, y = 5;
int result = multiply(x, y);
printf("Multiplication = %d\n", result);
return 0;
int multiply(int a, int b) {
return a * b;
}
Types Based on Parameters and Return Value:
1. No arguments, no return
2. Arguments, no return
3. No arguments, return
4. Arguments and return
Function Call Stack and Recursion:
C uses a stack to manage function calls.
Functions can call themselves - this is called recursion.
Example:
int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1);
Conclusion:
Functions in C are essential for writing efficient, organized, and maintainable code.
They enable modular design, reduce code duplication, and enhance code clarity.