Recursive program to find the Sum of the series 1 – 1/2 + 1/3 – 1/4 … 1/N
Given a positive integer N, the task is to find the sum of the series 1 – (1/2) + (1/3) – (1/4) +…. (1/N) using recursion.
Input: N = 3
1 – (1/2) + (1/3) = 0.8333333333333333
Input: N = 4
1- (1/2) + (1/3) – (1/4) = 0.5833333333333333
Approach: The idea is to form a recursive case and base case in order to solve this problem using recursion. Therefore:
- Base Case: The base case for this problem is when we have calculated the sum till the value of N in the denominator. Therefore, we stop the recursion when the counter variable ‘i’ reaches the value N.
- Recursive Case: The recursive case for this problem is to find whether the denominator is an even or odd. This is because, clearly, for every odd number, the preceding sign is a ‘+’ and for every even number, the preceding sign is a ‘-‘. Therefore, we check whether the counter variable is an even or odd number and accordingly add or subtract the value. Then, the function is recursively called for the next value of the value ‘i’.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.