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
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:
P.P.S. :Here are a few links to basic recursion tutorials
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.
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:
- Input the number of integers that have to be added (The value of n)
- Initialize an array to size n (arr)
- Loop till n and input all n integers into the array
- 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: - 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) - Otherwise return 0
(This is the exit case) - Print the result of the add() function (don't need to save the result)
- Exit
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)
Link to Code : Sum Of Array Elements Using Recursion
(Please Try To Refrain From Copying The Code)
No comments:
Post a Comment