Search code examples
javarecursionrecursive-datastructures

Converting iterative code to recursive code


I need some help with that function. I gonna use "val" in other functions but when I try to return the value in a recursive function just return 0. I need to make this loop in a recursive function Sorry for my English. Thanks a lot

int val = 0;
for (int i = 0; i < arreglo.length; i++) {
    if (arreglo[i] % 2 != 0) {
        val++;
    }
}

Solution

  • Here's a simple example how this can be done:

    For the base case of recursion you have to provide starting index and initial value, so pass 0 for index parameter and 0 for val parameter:

    public class Recursive{
         public static int recursive(int[] arreglo, int index, int val) {
             if (index == arreglo.length ) {
                 return val;
             } else {
                 if (arreglo[index] % 2 == 0) {
                     val++;  // increment value - even number
                 }
                 return recursive(arreglo, index+1, val);
             }
         }
     
         public static void main(String []args){
             int[] r = {1, 2, 3, 4, 5, 6, 7, 8};
             int result = recursive(r, 0, 0);
             System.out.println(result); // Outputs 4 
         }
    }