Home > database >  Java boolean recursion
Java boolean recursion

Time:11-13

I have an array of numbers should return true if 2 adjacent numbers divide by 10. For now its return always false.

public static boolean divideByTen(int arr[], int num) {
        int i = num - 1;
        if(i > 0) {
            divideByTen(arr, num - 1);
            if(arr[i]   arr[i - 1] % 10 == 0)
                return true;
        }return false;
        
    }

CodePudding user response:

divideByTen(arr, num - 1);

This invokes divideByTen (recurses) and throws away the result. Recursion isn't magic or special; you're just.. calling a method. It happens to be the same method you're in, but that's all. Calling a method without assigning its value to anything means the returned value is discarded.

Presumably, you wanted if (divideByTen(arr, num -1)) return true; instead.

CodePudding user response:

I tried to store the boolean value in one variable. I think in your case it will return false unless your if condition is not true at the end.

public static void main (String[] args) 
{
    int[] a = new int[] {1, 2, 3, 4, 1, 2, 30, 2};
    System.out.println(divideByTen(a, a.length - 1));
}



public static boolean divideByTen(int arr[], int num){
    boolean flag = false;
    
   if(num < 1){
       return flag;
   }
    
    flag = divideByTen(arr, num -1);
    
    if(num > 0){
        if((arr[num-1]   arr[num]) % 10 == 0){
            flag = true;
        }
    }
    return flag;
}
  • Related