Recursion in java
Recursion in java
Recursion in java
Assignment Solutions
Assignment Solutions
Q1 : Given an integer, find out the sum of its digits using recursion.
Input: n= 1234
Output: 10
Explanation: 1+2+3+4=10
Solution :
Code : ASS_Code1.java
Output :
Approach:
Let's define a function func which will take a number as input and will return the sum of all of its digits. now this
function can we written in this way first digit + sum of remaining digit (the same way human do sum in left to right
manner) but as extracting first digit is relatively tough thus we will start with last digit so the function func(num)
can be written as func(num) = last_digit + func(num after removing last digit). Now to get the last digit we can
use % operator and to remove the last digit we can use / operator.
Let's see the step-by-step approach for a better understanding of how the algorithm works
Q2: Given a number n. Find the sum of natural numbers till n but with alternate signs.
Constraints : 0<=n<=1e6
Input1 : n = 10
Output 1 : -5
Explanation : 1-2+3-4+5-6+7-8+9-10 = -5
Input 2 : n = 5
Output 2 : 3
Solution:
Code : ASS_Code2.java
Output :
and value returned by go(n,i+1). This is how we are recursively calling the go function.
Q3: Print the max value of the array [ 13, 1, -3, 22, 5].
Code: ASS_Code3.java
Output :
Approach
We start our function call from maxValue(arr, 5,0) which calls for maxValue(arr,5, 1) and so on. We will reach
our base case at the last index of the array. In this case, it will be index 4. In the base case, since we have only
one value, we can say that for the array portion starting from that index, the value itself is the max value that
we can get.
Using this the max value of the array part starting at index 3 will be calculated.
= max(22, 5)
= 22
Similarly,
= max(-3, 22)
= 22
= max(1, 22)
= 22
= max(13, 22)
= 22