In: Computer Science
Write a recursive method to sum the values in an array of integers. Create a file ArraySum.java and add the recursive method public int sumOfArray (). Use the driver class ArraySumDriver.java to populate your array and demonstrate that your method works.
////ArraySumDriver.java/////// public class ArraySumDriver { private final static int ARRAY_SIZE = 6; /** * @param args */ public static void main(String[] args) { int index = 0; Integer[] myArray = new Integer[ARRAY_SIZE]; ArraySum arraySum = new ArraySum(); myArray[index++] = 3; myArray[index++] = 5; myArray[index++] = 2; myArray[index++] = 6; int sum = arraySum.sumOfArray(myArray, 3); System.out.println(sum); myArray[index++] = 7; myArray[index++] = 1; sum = arraySum.sumOfArray(myArray, 5); System.out.println(sum); } }
JAVA PROGRAM
class ArraySum // create class ArraySum
{
//implement sumOfArray() method with two arugments
//First argument Integer array a and Second argument int size
public int sumOfArray(Integer a[],int size)
{
if(size<=0) return 0; // check condition size<=0 then return
0
return sumOfArray(a,size-1)+a[size-1]; // else, call recusively
sumOfArray() and calculate sum of array elements
}
}
// Implement Driver class ArraySumDriver
public class ArraySumDriver
{
// declre final static integer ARRAY_SIZE=6
// does not change ARRAY_SIZE it is final
private final static int ARRAY_SIZE=6;
public static void main(String [] args)
{
int index=0; // declare constant integer index=0
Integer [] myArray=new Integer[ARRAY_SIZE]; // create
Integer array object
ArraySum arraySum=new ArraySum(); // create instance
of ArraySum is arraySum
// declare array elements one by one
myArray[index++]=3;
myArray[index++]=5;
myArray[index++]=2;
myArray[index++]=6;
int sum=arraySum.sumOfArray(myArray,3); // calling
sumOfArray() method and return result sum
System.out.println(sum); // display sum of only first
3 elements in array
myArray[index++]=7;
myArray[index++]=1;
sum=arraySum.sumOfArray(myArray,5); // calling
sumOfArray() method and return result sum
System.out.println(sum); // display sum of only first
5 elements in array
}
}
OUTPUT
10
23