C program to find sum of even or odd number from 1 to n using recursion

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

Required knowledge

Basic C programming, Function, Recursion

Logic 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

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