C program to find sum of natural numbers in given range using recursion

Write a recursive function in C programming to find sum of all natural numbers between 1 to n. How to find sum of all natural numbers in C programming using recursion. Finding sum of all natural numbers using between a given range using recursion. Logic to find sum of natural numbers in given range using recursion in C programming.

Example

Input

Input lower limit: 1
Input upper limit: 10

Output

Sum of natural numbers from 1 to 10 = 55

Required knowledge

Basic C programming, Function, Recursion

Must know - Program to find sum of natural numbers in given range using loop

Declare recursive function to find sum of natural numbers

  1. First give a meaningful name to the function, say sumOfNaturalNumbers().
  2. Next the function must accept two inputs i.e. the lower and upper limit to find sum. Hence, pass two integer parameters to the function say sumOfNaturalNumbers(int start, int end).
  3. Finally, the function must return sum of natural numbers between start and end. Therefore the return type of function should be int.

The final function declaration to find sum of all natural numbers in given range is - int sumOfNaturalNumbers(int start, int end);.

Logic to find sum of natural numbers using recursion

Recursive function to find sum of natural numbers

Above is the mathematical recursive function to find sum of natural numbers. Where n is the lower limit and x is the upper limit and n=x is the base condition to exit control from function returning n. If n < x then return the value of recursive call to sum function + current number i.e. return start + sumOfNaturalNumbers(start + 1, end);.

Program to find sum of natural numbers using recursion

/**
 * C program to find sum of natural numbers from 1 to n using recursion
 */

#include <stdio.h>


/* Function declaration */
int sumOfNaturalNumbers(int start, int end);


int main()
{
    int start, end, sum;
    
    /* Input lower and upper limit from user */
    printf("Enter lower limit: ");
    scanf("%d", &start);
    printf("Enter upper limit: ");
    scanf("%d", &end);
    
    sum = sumOfNaturalNumbers(start, end);
    
    printf("Sum of natural numbers from %d to %d = %d", start, end, sum);
    
    return 0;
}


/**
 * Recursively find the sum of natural number
 */
int sumOfNaturalNumbers(int start, int end)
{
    if(start == end)
        return start;
    else
        return start + sumOfNaturalNumbers(start + 1, end); 
}

Output

Enter lower limit: 1
Enter upper limit: 100
Sum of natural numbers from 1 to 100 = 5050

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>