728x90
public class Cumulative {
// Recursive method
static double cumulativeSumRec(double [] array, int index){
// Base case: if index is 0, return the first element
if (index == 0) {
return array[0];
} else {
// Recursive case: sum of array[index] and cumulative sum of the rest
return array[index] + cumulativeSumRec(array, index - 1);
}
}
// Iterative method as an alternative
static double cumulativeSumIter(double [] array){
double sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
return sum;
}
public static void main(String[] args) {
double [] panda = {1.2, 2.5, 3.73, 4.48, 5.6, 6.9, 7.47, 8.37, 9.2, 10.36};
// Using the recursive function
double sumRecursive = cumulativeSumRec(panda, panda.length - 1);
// Using the iterative function, if needed
double sumIterative = cumulativeSumIter(panda);
System.out.println("Recursive sum: " + sumRecursive);
System.out.println("Iterative sum: " + sumIterative);
}
}
728x90
'호그와트' 카테고리의 다른 글
실제의 해킹을 잘하고 싶다면... (0) | 2023.11.12 |
---|---|
치킨버거 맛 좀 볼래요? (0) | 2023.11.09 |
honki mode on (0) | 2023.11.02 |
쥐를 잡자 냐옹아 (0) | 2023.11.01 |
영국 사진들 대공개 1 (0) | 2023.09.13 |