C Program To Find Sum of Natural Numbers Using Recursion


Write a recursive function to obtain the running sum of first 25 natural numbers.

1 + 2 + 3 + 4 + 5 + …. + 23 + 24 + 25 = 325

Related Read:
C Program to Calculate the Sum of Natural Numbers From 1 to N
C Program To Calculate the Sum of Natural Numbers From 1 to N using For Loop
Recursive Functions In C Programming Language

Video Tutorial: C Program To Find Sum of Natural Numbers Using Recursion


[youtube https://www.youtube.com/watch?v=EnUpKX5ps58]

YouTube Link: https://www.youtube.com/watch?v=EnUpKX5ps58 [Watch the Video In Full Screen.]


Source Code: C Program To Find Sum of Natural Numbers Using Recursion

#include<stdio.h>

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

int main()
{
    int count = 25;

    printf("Sum of 1st 25 natural numbers is %d\n", count, sum(count));

    return 0;
}

Output:
Sum of 1st 25 natural numbers is 325

Logic To Find Sum of Natural Numbers Using Recursion

25 is passed to a function sum, from main method. Inside function sum(), if the passed number is a non-zero then we add sum(num-1) to num. We keep doing it until num value is 0. Once num is 0, code inside else block gets executed and 0 is returned.

Source Code: Find Sum of Natural Numbers Using Recursion – Take input from user

#include<stdio.h>

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

int main()
{
    int count;

    printf("Enter a positive no\n");
    scanf("%d", &count);

    printf("Sum of 1st %d natural numbers is %d\n", count, sum(count));

    return 0;
}

Output 1:
Enter a positive no
5
Sum of 1st 5 natural numbers is 15

Output 2:
Enter a positive no
14
Sum of 1st 14 natural numbers is 105

Example:

Lets assume user has input num value as 5.
Recursive Call sum(num – 1).

numCalling FunctionReturned Value
5sum(5)
5sum(4)10
4sum(3)6
3sum(2)3
2sum(1)1
1sum(0)0
0return 0;

Value Returning – Control Shifting back.

num+sum(num-1)Return ValueResult
1 + sum(0)01 + 0 = 1
2 + sum(1)12 + 1 = 3
3 + sum(2)33 + 3 = 6
4 + sum(3)64 + 6 = 10
5 + sum(4)105 + 10 = 15

Finally, after completing the recursive calls and once num is equal to zero, sum() will return 15 to main().

i.e., 1 + 2 + 3 + 4 + 5 = 15.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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