Side Navigation

X

Find The Maximum Value in a List

Write a method that returns the largest integer in the list.
You can assume that the list has at least one element.
public class BestOnlineLearning {

    public static int maxNumber(int[] n){
       int max = n[0];
       for(int i=0; i<n.length; i++){
           if(n[i] > max){
               max = n[i];
           }
       }
       System.out.println(max);
       return max;
    }

    public static void main(String[] args) {
        int[] n = {2,4,5,6,7,8,9,0,1,3};
        maxNumber(n);
    }
}

(OR)

you can also use the for-each

for(int val : n){
   if(val > max){
       max = val;
   }
 }

 

You May Also Like

Comments

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>