C program to find sum of natural numbers between 1 to n 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.

Example:
Input upper limit to find sum: 100
Output: Sum of natural numbers from 1 to 10 = 55

Required knowledge

Basic C programming, Function, Recursion

Logic to find sum of natural numbers using recursion

If you are done with how to find sum of natural numbers from 1 to n using loop then logic to this program would not be difficult. Below is the recursion base condition for the recursive program to find sum of first n natural numbers:
sum(0) = 0 {Base condition}
sum(n) = n + sum(n-1)

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 sum(int N);


int main()
{
    int n, s;
    
    printf("Enter upper limit to find sum: ");
    scanf("%d", &n);
    
    s = sum(n); //Calls sum() function and stores the result in s
    
    printf("Sum of natural numbers from 1 to %d = %d", n, s);
    
    return 0;
}



/**
 * Recursively finds the sum of natural number from 1 to n
 */
int sum(int N)
{
    if(N == 0)
        return 0;
    else
        return (N + sum(N-1)); 
}


Output
Enter upper limit to find sum: 100
Sum of natural numbers from 1 to 100 = 5050

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment