6. Functions
Function declaration, definition, parameters, return values, and pass-by-value semantics in C.
Functions encapsulate behavior and enable reuse and testing.
- Declaration (prototype) vs definition
- Parameters and return values
- Pass-by-value semantics in C
Examples
Factorial (factorial.c)
A function that computes N! using a loop, demonstrating parameters and return values:
#include <stdio.h>
int main(void) {
int n;
printf("Enter N (0..12): ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial not defined for negative numbers.\n");
return 0;
}
unsigned long long fact = 1ULL;
for (int i = 1; i <= n; i++) {
fact *= (unsigned long long)i;
}
printf("%d! = %llu\n", n, fact);
return 0;
}
Add Two Numbers (add_two_numbers.c)
A minimal function that takes two parameters and returns their sum:
#include <stdio.h>
int add(int a, int b) { return a + b; }
int main(void) {
printf("add(3,4) = %d\n", add(3,4));
return 0;
}