Example:
Input upper limit to find sum: 100
Output: Sum of natural numbers from 1 to 10 = 55
Required knowledge
Basic C programming, Function, RecursionLogic 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
Sum of natural numbers from 1 to 100 = 5050
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find sum of even or odd numbers in given interval using recursion.
- C program to print all natural numbers within given interval using recursion.
- C program to find factorial of any number using recursion.
- C program to generate nth fibonacci term using recursion.
- C program to find GCD(HCF) of any two numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to display array elements using recursion.
- C program to find cube of any number using function.
- C program to find maximum and minimum between two numbers using functions.
- C program to check even or odd numbers using function.