Functions in C Programming
A function in C is a block of code that performs a specific task.
It helps in code reusability, modularity, and makes programs easy to understand.
Why use functions?
To avoid repeating the same code.
To make code cleaner and organized.
To divide large programs into smaller parts.Types of Functions
There are mainly two types:
1. Library Functions:
Already available in C libraries.
Examples:
printf()
scanf()
sqrt()
printf()2. User-Defined Functions
Functions created by the programmer.
Function Syntax
Function Example (Simple Addition)
Output:
Result = 15
Parts of a Function
Result = 15
- Function Declaration (Prototype)
Tells the compiler about the function name, return type, and parameters.
int add(int, int); 2. Function Definition
Actual body of the function.
int add(int a, int b) {
return a + b;
}
}
int add(int a, int b) {
return a + b; }
}
3. Function Call
Used to use/execute the function.
add(5, 10);
Types Based on Input/Output
1. Without arguments and without return
void greet() {
printf("Hello!");
}
2. With arguments but no return
void square(int x) {
printf("%d", x * x);
}
3. Without arguments but with return
int getNumber() {
return 10;
}
4. With arguments and return (Most common)
int multiply(int a, int b) {
return a * b;
}
Example: Function to Find Factorial
Benefits of Functions
Reduces code duplication
Makes debugging easier
Allows team collaboration
Helps in modular programming
Call by Value in C
In call by value, when you pass arguments to a function, a copy of the actual values is passed.
This means:
How Call by Value Works
Example
0 Comments