Sum of vectors in java

0

With the recursive algorithm, how is a vector addition program done in java?

int suma_vec(int v [], int n) {
    if (n == 0) {
        return v[n];
    } else {
        return suma_vec(v, n - 1) + v[n];
    } 
} 
    
asked by Stephanie B Bautista 21.03.2017 в 20:39
source

2 answers

2

If you want to recursively add the contents of an array whose elements are, for example, integers:

int[] vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

int suma_arreglo(a, i){
    if (i < a.length-1)
        acum = a[i] + suma_arreglo(a, i+1);
    else{
        acum = a[i];
        }
    return acum;
    }

System.out.print(suma_arreglo(vec, 0));

I tried it with Python and transcribed it in Java.

    
answered by 21.03.2017 в 22:07
0

To add an Array of integers recursively in Java you can follow the following example

int sum (int[] v, int idx){
    if(idx < 0 || idx >= v.length)
        throw new ArrayIndexOutOfBoundsException();
    return idx == 0 ? v[0] : v[idx] + sum(v , idx - 1) ;
}

int sum(int[] v){
    return sum(v, v.length - 1);
}

We add a RuntimeException for out-of-range indices and use a more compact construction. Using it is very simple

int [] v = new int[]{1,2,3,4,5};
sum(v) // Prints 15!
    
answered by 21.03.2017 в 22:34