C Program - Find the Sum of Natural Numbers using Recursion

#include <stdio.h>

int sum(int n) {
    if(n == 0)
        return 0;
    else
        return n + sum(n - 1);
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Sum = %d\n", sum(num));
    return 0;
}
Enter a positive integer: 5
Sum = 15
Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗