C Recursion
Compute a short triangular total while identifying the base case and the depth limit.
How it works
A recursive function calls itself on a smaller problem. It needs a base case that terminates the chain and a step that moves toward that case. Each call consumes implementation resources; C does not guarantee unlimited recursion or tail-call optimisation. This example deliberately limits n to a small range and computes the sum of one through n. For a large input, an iterative loop or a checked formula would be more appropriate than deep recursive calls.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror recursion.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
static unsigned triangular(unsigned n) {
if (n == 0) { return 0; }
return n + triangular(n - 1);
}
int main(void) {
unsigned n = 5;
if (n > 100) { return 1; }
printf("Triangular total: %u\n", triangular(n));
return 0;
}
Expected result
Triangular total: 15
The zero case returns without making another call. Every other call subtracts one, so the chain reaches zero for the unsigned nonnegative input. The chosen bound keeps the mathematical result representable even on a 16-bit unsigned implementation. It does not establish a portable stack-size guarantee; applications with strict resource limits should avoid relying on recursion depth.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.