C Program to Find the Sum of Natural Numbers using Recursion - Source Code, Output & Execution Flow

C Program to Find the Sum of Natural Numbers using Recursion

This C program calculates the sum of natural numbers using recursion.

#include <stdio.h>
int sum(int n) {
    if (n == 0) return 0;
    return n + sum(n - 1);
}
int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Sum = %d
", sum(n));
    return 0;
}
Enter a positive integer: 5
Sum = 15

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.