CBSE Class 12 Computer Science Question 26 of 56

Functions — Question 26

Back to all questions
26
Question

Question 22

Write a recursive function to add the first 'n' terms of the series:

1 + 1/2 - 1/3 + 1/4 - 1/5...............

Solution
def add_series_terms(n):
    if n == 1:
        return 1
    elif n % 2 == 0:
        return add_series_terms(n - 1) + 1 / n
    else:
        return add_series_terms(n - 1) - 1 / n

n = int(input("Enter the term: "))
print(add_series_terms(n))
Output
Enter the term: 2
1.5

Enter the term: 5
1.2166666666666668
Answer

def
add_series_terms
(
n
):
if
n
==
1
:
return
1
elif
n
%
2
==
0
:
return
add_series_terms
(
n
-
1
)
+
1
/
n
else
:
return
add_series_terms
(
n
-
1
)
-
1
/
n
n
=
int
(
input
(
"Enter the term: "
))
print
(
add_series_terms
(
n
))
Output
Enter the term: 2
1.5

Enter the term: 5
1.2166666666666668