Friday 10 August 2018

Sum Of Array Elements Using Recursion

QUESTION DESCRIPTION :

Given an array of integer elements, find sum of array elements using recursion.

TEST CASE 1

INPUT

5
1 2 3 4 5

OUTPUT

15


TEST CASE 2

INPUT

4
4 4 4 4

OUTPUT

16



EXPLANATION :

The question requires you to input a set of numbers and then find their sum using the recursive addition.
The number of integers is given in the first line say "n", then n space seperated integers follow.

ALGORITHM :

For this code, we will input the "n" value, which gives the numbers of integers to be added. Then initialize the array to n. Then input the n values in the array using a loop. Then instead of using a loop to traverse through the array we will simulate it using recursion.

Steps:

  1. Input the number of integers that have to be added (The value of n)
  2. Initialize an array to size n (arr)
  3. Loop till n and input all n integers into the array
  4. Call the add() function and pass the array and n to it.
    (Set the return type of function to be int)

    Inside the add() function:
    1. If there are more values available, i.e. n>0, return the current arr[n] value and call the add function again with n-1 as the argument.
      (This is the recursive base case)
    2. Otherwise return 0
      (This is the exit case)
  5. Print the result of the add() function (don't need to save the result)
  6. Exit
P.S. It is a bit difficult to explain recursive algorithms and recursive statements. It is recommended to read the code and try to understand. Ask doubts in the comments.

P.P.S. :Here are a few links to basic recursion tutorials
SOLUTION : (Please use this as reference only)

Link to Code : Sum Of Array Elements Using Recursion

(Please Try To Refrain From Copying The Code)

No comments:

Post a Comment