Trace factorial (n!) on paper: expand fact(5) down to fact(1)
Confirm there's always a base case
Start with small depths (3 to 5)
Notice that the same logic can be written iteratively β try writing both versions
π‘ Tip: 90% of recursion bugs come down to a missing or unreachable base case, or forgetting to shrink the argument. Check those first.
Functions with return values
A function takes parameters, performs a computation, and can return a value to the caller.
intsquare(int n) { // return type: intreturn n * n; // return a value
}
intmain(void) {
int r = square(5); // call the function; r becomes 25printf("%d\n", r);
}
Argument
The value passed to the function. Goes inside the parentheses.
Return value
The result the function sends back, via the return statement.
name(args)
A call expression. Its value is whatever the function returns.
void — "nothing"
Use void to indicate "no parameters" or "no return value."
// no return, no parametersvoidsayHello(void) {
printf("Hello!\n"); // return can be omitted
}
// no return, with parametervoidprintBox(int n) {
for(int i=0; i<n; i++) printf("*");
printf("\n");
}
// returns a value, no parametersintgetAnswer(void) {
return42;
}
The main function:int main(void) means "no parameters, returns an int."
Multiple parameters & types
You can pass multiple parameters separated by commas. Each one needs its own type declaration.