Friday, May 21, 2010

Writing a java code Find the minimum value of an array of 3 numbers?

I am new to Java and was wondering if any one could show me how to do this , or at least how to separate the values of the array in to separate variables that i can use the Min function on.

Writing a java code Find the minimum value of an array of 3 numbers?
All you need to do is select the elements that you want to compare.





Math.min(numbers[0], numbers[1]);





A for loop would work nicely for that code.
Reply:I'm surprised at the complexity of the answers. You said that you are a newbie and so I think something like this is better:





suppose you want to find the minimum of array A:





double min = A[0] ;


for ( int k=0; k%26lt;A.length; k++ )


{


if ( A[k] %26lt; min ) min = A[k];


}





Naturally if your array is integers then you'd declare min as int:


int min = A[0] ;





Notice that you can use A.length to get the length of the array. length is not a method but rather an instance variable of the array A.





There is a change that uses a nice operator:


replace the if with:





min = ( (A[k]%26lt;min)?A[k]:min) ;
Reply:The explanation I'm going to give you will work for all Arrays of Integers (with a modification for Doubles presented at the end):





In Java, there is a property of Integers called Integer.MAX_VALUE. If you create an int (I'll call it "test") and initialize it to Integer.MAX_VALUE, you can then run a for-loop like this (assuming yourArrayName is the name of your array variable):


for(int i=0; i%26lt;yourArrayName.length; i++)


This will run through the entirety of your array.


Within the loop, you need to test if yourArrayName[i] (the value in "i" location of the array) is less than the value of test. If it is, you need to set the value of test to yourArrayName[i].





This will consistently find the smallest value of yourArrayName because test will be automatically reset to the first value of yourArrayName on the first iteration of the loop.





The min() function will not handle Arrays natively. This code could be changed to account for doubles by making test a double and using the Double.MAX_VALUE value.


No comments:

Post a Comment