-1

In this code, -20 should be the min since its negative and the farthest from zero correct? But when I run MinAlgoritm, the integer 5 is printed out. I have a Max version of this that works fine but this doesn't. How can this be? Are there any improvements I can make?

class MinAlgorithm
{
public static void main ( String[] args ) 
 {
   int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
   int   min;
   // initialize the current minimum
   min = array[0];
   // scan the array
   for ( int index=0; index < array.length; index++ )
     { 
       if (array[index]<min);

       min=array[index];
     }
   // Print out the result
   System.out.println("The minimum of this array is: " + min );
 }
}      

4 Answers4

1

Change

   if (array[index]<min);
                        ^
       min=array[index];

to

   if (array[index]<min)
       min=array[index];

Your extra ; ends the if statement, so min=array[index]; is always executed, regardless of whether array[index]<min is true or not.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Remove semicolon from line if (array[index]<min);

Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
1

try this :)

class MinAlgorithm
{
    public static void main ( String[] args ){   
        int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
        int   min;
        // initialize the current minimum
        min = array[0];
        // scan the array
        for ( int index=0; index < array.length; index++ ){ 
            if (array[index]<min){
                min=array[index];
            }
        }
        // Print out the result
        System.out.println("The minimum of this array is: " + min );
    }
}    

Your code is not working because of that ";" after if

Vishnu
  • 375
  • 4
  • 16
0

I believe there is a semicolon after the if clause, rendering it useless. That's why 5 is the min, because it's the last number to assign as min.

Hugo M. Zuleta
  • 572
  • 1
  • 13
  • 27