anit
anit

Reputation: 11

printing the max of an array- Java

Write a piece of code that examines an array of integers and reports the maximum value in the array to System.out. Consider putting your code into a method called max that accepts the array as a parameter and returns the maximum value. Assume that the array contains at least one element. Your method should not modify the elements of the array.

This is what i have:

public int max(int []a)
{
int maxVal=0;
for(int i=0;i<a.length;i++)
    {
        if(a[i]>maxVal)
            {
                maxVal=a[i];
            }
        }
        return maxVal;
    }

Problem is that it doesnt work for the values of max({-4, -5, -3, -6}).

How can i fix this to work for that test as well as all others?

Upvotes: 1

Views: 4302

Answers (2)

technocrat_13
technocrat_13

Reputation: 1

There is another more helpful way;

import java.util.Arrays;

sort your arrays by -

Arrays.sort(array);

then -

int c = array.length;
System.out.println(array[c-1]);

Upvotes: 0

Vinit
Vinit

Reputation: 1825

public int max(int []a)
 { 
int maxVal=a[0];
 for(int i=0;i<a.length;i++)
 { 
if(a[i]>maxVal) 
{
 maxVal=a[i];
 }
 } return maxVal;
 } 

Upvotes: 3

Related Questions