Header Ads

C Program to Find the Sum of Natural Numbers using Recursion

C Program to Find the Sum of Natural Numbers using Recursion
The positive numbers 1, 2, 3... are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using the loop as well. However, you will learn to solve this problem using recursion here.

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

Enter a positive integer: 20
Sum = 210


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Powered by Blogger.