Ca) write an iterative program which calculate As an Example test youir arrauy w
ID: 3589181 • Letter: C
Question
Ca) write an iterative program which calculate As an Example test youir arrauy with 5 elements sum of the integers in an array. Bonus Cb) write a recursive program which calculates the sum of the elements of the array according to the algorithm below. consider this definition of the sum of the elements in an integer array: sum( array, index ) = 0, if index-array .1 ength sum( array, index ) array [index]+sum array, index+1), if index array.1ength write a Java method that impiements this definition and a program to test it. method should look something like: int sum int[] array, int index ) The testing program will call sum testArray, 0Explanation / Answer
class Arraysum
{
static int array[] = {12,5,4,6,8};
//Method to sum the elements of array
static int sum(){
int i;
int sum = 0;
for(i=0; i<array.length; i++)
sum += array[i];
return sum;
}
//Recursive method to sum the elements of array
static int sumRecursive(int [] arr, int index){
if(index == arr.length)
return 0;
return arr[index] + sumRecursive(arr, index+1);
}
public static void main(String[] args){
System.out.println("Sum of elements of array: "+ sum());
System.out.println();
System.out.println("Recursive sum of elemenst of array: "+ sumRecursive(array,0));
}
}