logo Practice-It logo

arraySum

Language/Type: Java arrays
Author: Marty Stepp

Write a method named arraySum that accepts two arrays of real numbers a1 and a2 as parameters and returns a new array a3 such that each element of a3 at each index i is the sum of the elements at that same index i in a1 and a2. For example, if a1 stores {4.5, 5.0, 6.6} and a2 stores {1.1, 3.4, 0.5}, your method should return {5.6, 8.4, 7.1}, which is obtained by adding 4.5 + 1.1, 5.0 + 3.4, and 6.6 + 0.5.

If the arrays a1 and a2 are not the same length, the result returned by your method should have as many elements as the larger of the two arrays. If a given index i is in bounds of a1 but not a2 (or vice versa), your result array's element at index i should be equal to the value of the element at index i in the longer of a1 or a2. For example, if a1 stores {1.8, 2.9, 9.4, 5.5} and a2 stores {2.4, 5.0}, your method should return {4.2, 7.9, 9.4, 5.5}.

The table below shows some additional calls to your method and the expected values returned:

Arrays Call and Value Returned
double[] a1 = {4.5, 2.7,  3.4, 0.8};
double[] a2 = {1.4, 8.9, -1.0, 2.3};
arraySum(a1, a2) returns {5.9, 11.6, 2.4, 3.1}
double[] ax = {2.4, 3.8};
double[] ay = {0.2, 9.1, 4.3, 2.8, 1.4};
arraySum(ax, ay) returns {2.6, 12.9, 4.3, 2.8, 1.4}
double[] aa = {1.0, 2.0, 3.0};
double[] ab = {4.0, 5.0};
arraySum(aa, ab) returns {5.0, 7.0, 3.0}
double[] ai = {};
double[] aj = {42.0};
arraySum(ai, aj) returns {42.0}

For full credit, you should not modify the elements of a1 or a2. You may not use a String to solve this problem.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.