Functions & Recursion

⚙️ C Language 🟢 Lesson 7 of 20 📅 2026 Edition
Functions let you break a large program into small, reusable, testable pieces. C requires you to declare exactly what type of value a function returns and what types of arguments it accepts, which helps the compiler catch mistakes before your program ever runs.
1Defining and Calling a Function
C Language ▶ Run Code
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.

2Function Prototypes

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:

C Language ▶ Run Code
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;
}
3Pass by Value

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():

C Language ▶ Run Code
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.

4Recursion

A recursive function calls itself to solve a smaller version of the same problem, until it reaches a base case that stops the recursion:

C Language ▶ Run Code
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.

⚠️ Common Mistake: Writing Recursion Without a Base Case

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.

💻 Try It Yourself

Write a recursive function that calculates the sum of all numbers from 1 to n, and test it with n = 10.

C Language ▶ Run Code
#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;
}
Run This in Our Compiler →