Friday, April 11, 2008

Find the Maximum

Write a function which finds the maximum number in an array or numbers.


This problem ensures you know how to implement a loop and search in an array.


public class FindMax {
/** @param a an array of integers of length > 0
Returns the maximum integer in a */

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

//Do some unit testing
public static void main (String [] argv){
int[] a = new int[5];
a[0] = 1; a[1] = 3; a[2] = 2; a[3] = 7; a[4] = 5;
System.out.println(findMax(a));
}
}

1 comment:

Jerome said...

I've done this programming problem on my blog. Here .

ShareThis