1

It gives me out of bound exception. And it seems not to recognize the first element in the array.

public class MaximumRec {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] A = {90, 45,12,19,72,55,15,19};
        int x = maximumR(A,8);
        System.out.print(x);

    }

    static int maximumR(int[] A, int n)
    {
        int max;
        if (n == 1)
        {
            return A[n];
        }
        else
        {
             max = maximumR(A, n-1);
             if(max < A[n] )
             {
                 max = A[n];
             }
        }
        return max;
    }

}
2
  • 2
    You need to start at 7, you only have 8 elements in your array. Arrays are 0 based, so you need to check if n==0. Commented Mar 29, 2018 at 21:25
  • Thank you. I just assigned 7 to n. However my output result is 72 instead of 90. I don't know what is wrong. Commented Mar 29, 2018 at 22:36

2 Answers 2

1

It's because of the 8 you assign to n. And then you ask for the 8th element in the array, but the array starts counting at 0 so the A[8] doesn't exists. The max is A[7].

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I just assigned 7 to n, however my output is 72, instead of 90. I can't figure out what is wrong
0

Java follows C-style indexing or Zero-based numbering in which index starts from 0 instead of 1. Also a good practice would be to dynamically assign the number instead of hard coding it.

e.g.

int x = maximumR(A, A.length - 1);

2 Comments

Thank you, I just assigned 7 to n, however my output is 72, instead of 90. I can't figure out what is wrong
It is because of your base condition in the recursion. The correct base condition in the recursion would be n==0 instead of n==1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.