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
Till now we have learnt various techniques of checking even or odd numbers such as using bitwise operators, conditional operator, if else, switch case and we also know how to find sum of all even numbers or sum of odd numbers from 1 to n using loop. Logic to find sum of even or odd numbers using recursion 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 ;)
You may also like
- Function and recursion programming exercises index.
- C program to print all natural numbers from 1 to n using recursion.
- C program to print all even or odd numbers from 1 to n using recursion.
- C program to find power of any number using recursion.
- C program to check whether a number is palindrome or not using recursion.
- C program to find sum of digits of any number using recursion.
- C program to print array elements using recursion.
- C program to find sum of all array elements using recursion.
- C program to find all perfect numbers using function.
- C program to find all armstrong numbers using function.
- C program to find maximum or minimum between two numbers using function.