Functions & Recursion
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("%d\n", result);
return 0;
}
The int before add declares the function's return type — the type of value it will hand back. A function that doesn't return anything uses void as its return type instead.
If a function is defined after main() in your file, you must first declare it above main() with a prototype, so the compiler knows it exists:
int add(int a, int b); // prototype - note the semicolon, no body
int main() {
printf("%d\n", add(2, 3));
return 0;
}
int add(int a, int b) { // actual definition
return a + b;
}
When you pass a variable into a C function, the function receives a copy of its value — changes made inside the function do not affect the original variable back in main():
void tryToChange(int x) {
x = 100; // only changes the local copy
}
int main() {
int number = 5;
tryToChange(number);
printf("%d\n", number); // still prints 5!
return 0;
}
To actually modify the original variable, you need pointers, covered in Lesson 13.
A recursive function calls itself to solve a smaller version of the same problem, until it reaches a base case that stops the recursion:
int factorial(int n) {
if (n <= 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case
}
Every recursive function needs a base case — without one, it calls itself forever until the program crashes with a stack overflow.
A recursive function that never reaches a stopping condition keeps calling itself indefinitely, eventually exhausting the program's call stack and crashing with a stack overflow error. Always write and test your base case first, before adding the recursive call.
Write a recursive function that calculates the sum of all numbers from 1 to n, and test it with n = 10.
#include <stdio.h>
int sumToN(int n) {
if (n <= 1) {
return n;
}
return n + sumToN(n - 1);
}
int main() {
printf("Sum: %d\n", sumToN(10));
return 0;
}