add values of an array with recursion [duplicate]

0

I have to perform the sum of the values of an array using recursion (exercise for university) I am not able to make the recursive call by passing an array, I leave the code in case you can give me a hand.

Code:

import java.util.Scanner;

public class EjercicioDoce {


    public static void main(String[] args) {


        Scanner sc = new Scanner(System.in);


        System.out.println("Cuantos numeros quiere ingresar?");
        int arr[] = new int[sc.nextInt()];

        System.out.println("Cargar los Valores :");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.println(sumarValores(arr));
    }



        public static int sumarValores(int array[]) {
            int tam = array.length;
            int rta;
            if (tam == 0){
                return 1;
            }else{
                 rta = (array[tam]) +  sumarValores(array[tam-1]);;

            }
            return rta;
        }
    }
}
    
asked by Maxi Hernandez 19.09.2017 в 12:42
source

1 answer

1

The problem you have is in the method call because the method requires a array as the input parameter but in the line rta = (array[tam]) + sumarValores(array[tam-1]); the array[tam-1] what it is recovering is the value in the tam-1 position of the array (A number in this case)

One possible solution would be the following:

  

EDITED: Added comments to the code.

Scanner sc = new Scanner(System.in);

        System.out.println("Cuantos numeros quiere ingresar?");
        int arr[] = new int[sc.nextInt()];

        System.out.println("Cargar los Valores :");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        // LLAMADA A LA FUNCIÓN PARA SUMAR LOS VALORES DE UN ARRAY DE FORMA RECURSIVA
        System.out.println(sumarValores(arr, arr.length - 1));
    }

    // EL MÉTODO RECOGERÁ EL ARRAY Y LA POSICIÓN DEL ELEMENTO A SUMAR
    public static int sumarValores(int array[], int posArray) {
        // INICIALIZAMOS UNA VARIABLE CON LA POSICIÓN DEL ARRAY ((NO ES NECESARIO)) 
        int tam = posArray;
        int rta;
        /* COMPROBAMOS QUE ÉL TAMAÑO DEL NO SEA CERO, YA QUE SI EL TAMAÑO
        ES CERO INTENTARÁ EN LA SIGUIENTE LLAMADA ENTRAR EN LA POSICIÓN -1
        DEL ARRAY DANDO UN ERROR */
        if (tam == 0) {
            return array[tam];
        } else {
            /* SI EL TAMAÑO NO ES IGUAL A CERO, AÑADIMOS AL RESULTADO
            LA SUMA DEL VALOR PASADO POR PARÁMETRO MÁS EL VALOR DE LA 
            POSICIÓN ANTERIOR */
            rta = (array[tam]) + sumarValores(array, tam - 1);

        }
        return rta;
    }
  

Note: The method (function) is being called starting from the last position in the array and decrementing until the first, when the    array [0]

Example:

If we have an array of 5 positions loaded with 5 number and the function is called

int array[] = {2,4,1,3,5};
int posicionAnterior = array.length;
sumarValores(array, posicionAnterior);

The function will perform the following operation in this order:

  • Enter and initialize the parameter int tam
  • check if the size is equal to zero or not * (the first time in this example is not) *
  • Then it will go through the else and add the array [tam], which will be 5 the first time, with the returned by the function
  • The function will enter recursively until it reaches the first value of the array array[0] (which in this example is 2) . From this point it will go up Returning "2" and adding it to the value from where it was called (in this case the next position that is worth 4). You will thus pass to a higher step adding the returned values:

  • When array [0] return - > 2
  • When array [1] return - > 2 + 4
  • When array [2] return - > 6 + 1
  • When array [3] return - > 7 + 3
  • When array [4] return - > 10 + 5
  • answered by 19.09.2017 в 13:03