File tree 1 file changed +45
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 4 - Recursion I
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given an array of length N, you need to find and return the sum of all elements of the array. Do this recursively.
3
+
4
+ Input Format :
5
+ Line 1 : An Integer N i.e. size of array
6
+ Line 2 : N integers which are elements of the array, separated by spaces
7
+
8
+ Output Format :
9
+ Sum
10
+
11
+ Constraints :
12
+ 1 <= N <= 10^3
13
+
14
+ Sample Input 1 :
15
+ 3
16
+ 9 8 9
17
+ Sample Output 1 :
18
+ 26
19
+
20
+ Sample Input 2 :
21
+ 3
22
+ 4 2 1
23
+ Sample Output 2 :
24
+ 7
25
+ */
26
+
27
+ public class SumArray {
28
+
29
+ public static int sum (int input []) {
30
+
31
+ if (input .length ==1 )
32
+ {
33
+ return input [0 ];
34
+ }
35
+
36
+ int [] smallOutput = new int [input .length -1 ];
37
+ for (int i =0 ;i <input .length -1 ;i ++)
38
+ {
39
+ smallOutput [i ]=input [i ];
40
+ }
41
+
42
+ int output =input [input .length -1 ]+sum (smallOutput );
43
+ return output ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments