Question

Can anyone help me to figure out how to get the sum from 2 different lengths of array. I am trying for to long but couldn't figure it out. I know that I need to have another loop. Here is my food until now

import java.util.Arrays;
import java.lang.*;
public class Question1d{
public static void main (String [] args){
    double[] b = add(); 
    System.out.println(Arrays.toString(b)); 
}

public static double[] add(){
    double[] v = {1, 2, 3, 4, 5, 4};
    double[] w = {5, 4, 3, 3, 1};
    int a = v.length;
    int b = w.length;
    int capacity = Math.max(a,b);
    double[] s = new double[capacity];
    if (a==b){
        for (int i = 0; i<capacity; i++){
            s[i] = v[i] + w[i];
        }
    }

    return s;
} 
}

Or maybe there is another way. Thnx

eddit: The method should return a new array of double formed by adding the corresponding elements of the input arrays. If one array is longer the sum should get elements of that array and the other array to be considerate as it has 0 values.

Was it helpful?

Solution

Something like this maybe?

public static double[] add(){
    double[] v = {1, 2, 3, 4, 5, 4};
    double[] w = {5, 4, 3, 3, 1};
    int a = v.length;
    int b = w.length;
    int capacity = Math.max(a,b);
    double[] s = new double[capacity];
    for (int i = 0; i<capacity; i++){
        s[i] = (i >= v.length ? 0 : v[i]) +  (i >= w.length ? 0 : w[i]);
    }


    return s;
} 

OTHER TIPS

If you want to count sum of two arrays, just count sum of the first, then count sum of the second and finally sum of these two numbers.

    int sum1 = 0;
    for (int i : v)
        sum1 += i;

    int sum2 = 0:
    for (int i : w)
        sum2 += i;

    int result = sum1 + sum2;

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top