Write an algorithm to obtain the sum of the first ten terms of the sequence using recursion. Also give iterative algorithm.
Q.) Write an algorithm to obtain the sum of the first ten terms of the sequence using recursion. Also give iterative algorithm.
Subject: Data StructuresRecursive Algorithm:
- Define a recursive function
sum_of_terms(n)
that takes an integern
as input and returns the sum of the firstn
terms of the sequence. - In the base case, when
n
is equal to 1, return 1. This is because the sum of the first term of the sequence is simply the first term itself. - In the recursive case, when
n
is greater than 1, calculate the sum of the firstn-1
terms of the sequence using the recursive callsum_of_terms(n-1)
. Then, add then
-th term of the sequence to this sum and return the result.
Here is the recursive algorithm in Python:
def sum_of_terms(n):
"""
Calculates the sum of the first n terms of the sequence.
Args:
n: The number of terms to sum.
Returns:
The sum of the first n terms of the sequence.
"""
# Base case: When n is equal to 1, return 1.
if n == 1:
return 1
# Recursive case: When n is greater than 1, calculate the sum of the first n-1 terms of the sequence
# using the recursive call sum_of_terms(n-1). Then, add the n-th term of the sequence to this sum and
# return the result.
else:
return sum_of_terms(n-1) + n
Iterative Algorithm:
- Initialize a variable
sum
to 0. This variable will store the sum of the firstn
terms of the sequence. - Initialize a variable
term
to 1. This variable will store the current term of the sequence. - Iterate over the numbers from 1 to
n
. - In each iteration, add the current term to the sum.
- Calculate the next term in the sequence by adding 1 to the current term.
- Repeat steps 3-5 until all the terms from 1 to
n
have been processed.
Here is the iterative algorithm in Python:
def sum_of_terms(n):
"""
Calculates the sum of the first n terms of the sequence.
Args:
n: The number of terms to sum.
Returns:
The sum of the first n terms of the sequence.
"""
# Initialize the sum and the current term.
sum = 0
term = 1
# Iterate over the numbers from 1 to n.
for i in range(1, n+1):
# Add the current term to the sum.
sum += term
# Calculate the next term in the sequence.
term += 1
# Return the sum of the first n terms of the sequence.
return sum