+ 1
If you know recursion then help me 😌
Q) print sum of an array ? i have solved it by passing two arguments into function i want to print just passing an array and it must be solved with recursion. check my attempt here 👇 https://code.sololearn.com/c0j1888T4c6C/?ref=app Guys what if i don't pass length of an array into function?? how can i print the same result ? i mean to say this 👇 public static int sum(int input[ ]) { // code here }
3 ответов
+ 3
Davinder Kumar
You pass length of array (do -1) or a reference (do +1), both will work in same way.
If you don't want both then you can do like this.
As we can't change length of array but we can copy array into another array by copyOf method of Arrays class
https://code.sololearn.com/cMrly9ZcMA1I/?ref=app
+ 1
Davinder Kumar
Without passing reference variable I think not possible with just passing array. So you pass length or with 0 value
public static int sum(int arr[], int i) {
if (arr.length == i)
return 0;
else
return sum(arr, i + 1) + arr[i];
}
public static void main(String[] args) {
int num[] = {9, 8, 9, 8};
int i = 0;
System.out.print(sum(num, i));
}
+ 1
A͢J sir I'm not talking about refrence variable I'm talking about length of array . Can't we solve with just passing array exception of its length ? As you added i variable but what if we don't add it .