Write a recursive function in C programming to find the sum of all even or odd numbers in a given range. How to find the sum of all even numbers between 1 to n using recursion in C programming. How to find sum of all odd numbers between 1 to n using recursion in C programming.
Example:
Input range: 100
Output: Sum of even numbers between 1 to 100 = 2550
sum(0) = 0 {Base condition}
sum(n) = n + sum(n-2){Where n is always even}
Recursive condition for sum of all odd numbers using recursion would be:
sum(1) = 1 {Base condition}
sum(n) = n + sum(n-2) {Where n is always odd}
Here in the below program what I have tried is to, embed the logic of both even and odd recursive condition in a single function.
Happy coding ;)
Example:
Input range: 100
Output: Sum of even numbers between 1 to 100 = 2550
Required knowledge
Basic C programming, Function, RecursionLogic to find sum of even or odd numbers recursively
Logic to this program is not very different from the program to find sum of natural numbers using recursion. Logic of both the programs are almost identical with a little change in recursive function. Below is the recursive conditions for sum of even numbers:sum(0) = 0 {Base condition}
sum(n) = n + sum(n-2){Where n is always even}
Recursive condition for sum of all odd numbers using recursion would be:
sum(1) = 1 {Base condition}
sum(n) = n + sum(n-2) {Where n is always odd}
Here in the below program what I have tried is to, embed the logic of both even and odd recursive condition in a single function.
Program to find sum of even or odd numbers using recursion
/**
* C program to find sum of all even or odd numbers between 1 to n using recursion
*/
#include <stdio.h>
int sum(int num);
int main()
{
int num, lastEven, lastOdd;
//Reads the upper limit to find sum from user
printf("Enter the upper limit to find sum: ");
scanf("%d", &num);
lastEven = (num & 1) ? num-1 : num; //Finds last even number in range
lastOdd = (num & 1) ? num : num-1; //Finds last odd number in range
printf("Sum of all even numbers from 1 to %d = %d\n", num, sum(lastEven));
printf("Sum of all odd numbers from 1 to %d = %d\n", num, sum(lastOdd));
return 0;
}
/**
* Finds the sum of all even or odd numbers recursively.
*/
int sum(int num)
{
//Base condition
if(num <= 0)
return 0;
/* Recursively calls sum() to add previous even or odd number */
return (num + sum(num-2));
}
Output
Enter the upper limit to find sum: 100
Sum of all even numbers from 1 to 100 = 2550
Sum of all odd numbers from 1 to 100 = 2500
Sum of all even numbers from 1 to 100 = 2550
Sum of all odd numbers from 1 to 100 = 2500
Happy coding ;)