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 Structures

Recursive Algorithm:

  1. Define a recursive function sum_of_terms(n) that takes an integer n as input and returns the sum of the first n terms of the sequence.
  2. 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.
  3. In the 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.

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:

  1. Initialize a variable sum to 0. This variable will store the sum of the first n terms of the sequence.
  2. Initialize a variable term to 1. This variable will store the current term of the sequence.
  3. Iterate over the numbers from 1 to n.
  4. In each iteration, add the current term to the sum.
  5. Calculate the next term in the sequence by adding 1 to the current term.
  6. 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