Functions in C Complete Guide v2
Functions in C Complete Guide v2
1. Introduction to Functions
A function is a block of code that performs a specific task. It allows code reuse and modular programming.
2. Structure of a Function
#include <stdio.h>
int main() {
greet(); // Function call
return 0;
}
3. Types of Functions
A function can take parameters (arguments) and return a value to the caller.
#include <stdio.h>
int main() {
int sum = add(5, 3);
printf("Sum: %d\n", sum);
return 0;
}
1. Call by Value: A copy of the variable is passed. Changes made do not affect the original value.
2. Call by Reference: The address of the variable is passed. Changes made affect the original value.
void changeValue(int a) {
a = 10;
}
int main() {
int x = 5;
changeValue(x);
printf("%d\n", x); // Outputs 5 (unchanged)
return 0;
}
int main() {
int x = 5;
changeValue(&x);
printf("%d\n", x); // Outputs 10 (changed)
return 0;
}
6. Recursive Functions
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
7. Summary