0

The following code will always write 0. Why is that and how do I fix it?

public static void main(String[] args) 
{
 int[] Array= {5,4,6,3,7,2,8,1,9,0};
 int max=0;
 System.out.println(maximum(Array,Array.length-1,max));
}
public static int maximum(int[] Array,int length,int max)
{
 if (length!=0)
 {
 if(max<Array[length])
 {
 max=Array[length];
 }
 maximum(Array,length-1,max); 
 }
 return max; 
}
asked Apr 13, 2017 at 16:51
4
  • What result are you getting? Commented Apr 13, 2017 at 16:57
  • Please elaborate on what you mean by "not working". Commented Apr 13, 2017 at 16:59
  • 1
    means it always get 0 in return Commented Apr 13, 2017 at 17:08
  • @ShahiryarArif I edited to reflect that, hope that's OK. Commented Apr 13, 2017 at 17:13

1 Answer 1

2

When you call maximum recursively, you don't write returned value.

 if (length!=0)
 {
 if(max<Array[length])
 {
 max=Array[length];
 }
 max = maximum(Array,length-1,max); //rewrite max variable
 }
 return max;

EDIT

And need to initialize first max value to Array[0]

int max=Array[0];
System.out.println(maximum(Array,Array.length-1,max));
answered Apr 13, 2017 at 16:59

2 Comments

@ShahiryarArif Also, it should be length != -1 - right now, if the maximum is the first item in the array, it'll only give the second-highest number.
@ShahiryarArif - I changed my answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.