C Program to Find the Sum of Natural Numbers Using Recursion

In this post, we will learn how to find the sum of natural numbers using recursion in C Programming language.

C Program to Find the Sum of Natural Numbers using Recursion

Natural Numbers are a part of the number system which includes all the positive integers from 1 till infinity and are also used for counting. For example: 1, 2, 3, 4, 5, 6, 7, . . . , and so on.

In the program, we will calculate the sum of natural numbers using recursion. For example: The Sum of the first 5 Natural Numbers is (1 + 2 + 3+ 4 + 5) = 15.

So, without further ado, let’s begin this tutorial.

C Program to Find the Sum of Natural Numbers using Recursion

// C Program To Find the Sum of Natural Numbers Using Recursion
#include <stdio.h>
int Sum(int n);
int main(){
    int num;
    
    // Asking for Input
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Sum of %d Natural Numbers is %d.", num, Sum(num));
    return 0;
}

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

Output

Enter a number: 7
Sum of 7 Natural Numbers is 28.

How Does This Program Work ?

    int num;

In this program, we have declared an int data type variable named as num.

    // Asking for Input
    printf("Enter a number: ");
    scanf("%d", &num);

Then, the user is asked to enter a number. The value of this number will get stored in num named variable.

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

Here, we have defined a custom function named Sum which will calculate and returns the sum of natural numbers.

Suppose, the user enters the number 5.

Initially, the function Sum() is called from main() with 5 passed as an argument. Then, the number 5 is added to the result of Sum(4).

In the next call, 4 is added to the result of Sum(3). This process continues until n = 0.

When n = 0, our recursive calls terminate and this returns the sum of integers to the main() function.

Conclusion

I hope after going through this post, you understand how to find the sum of natural numbers using recursion in C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *