Add some elements of an array in java [closed]

-1

They ask me to do a function in java in which the user passes a vector by parameters and the indexes in which he wants the sum to be made, that is, if I pass any vector t and the indexes 2 and 5 ( sum (t, 2,5)) would have to return the sum of the elements of the vector from index 2 to index 5. The syntax must be the following sum (int [] vecteros, int a, int b) { }

    
asked by Floppy 05.12.2018 в 15:13
source

1 answer

0

you have to create a cycle that adds up the ranges of the indices, you have to take into account that the indices do not exceed the size of the vector and that a > b in all cases

public class JavaApplication3 {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        int [ ] vector = { 2, 7, 4, 7, 15 };
        System.out.println(suma(vector, 2,4));
    }

    public static int suma(int[]vecEnteros, int a , int b){
        try{
        int suma=0;
        for (int i = a; i <= b; i++) {
            suma+=vecEnteros[i];
        }
        return suma;
        }catch(ArrayIndexOutOfBoundsException ex){
        return 0;
        }
    }

}
    
answered by 05.12.2018 / 15:56
source