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

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...