  | 
    
 
  
    
    
      
        
          
         Author | 
        
         Topic: Finding the largest value of an array   (Read 1834 times) | 
       
     
     | 
   
 
  
    
    
      
        
        
          
            
            REAS 
 
 
        
      
             | 
            
            
            
              
                
                Finding the largest value of an array  
                «  on: Oct 31st, 2002, 12:52am » | 
                
                
 
                 | 
               
             
             
            
            // The maxVal() method returns the largest value of an array        int[] numbers = { 90, 150, 30 };        void loop()     {      int largestNum = maxVal(numbers);      println(largestNum);    }        int maxVal(int[] testArray)     {      int maximum = Integer.MIN_VALUE; //initialize to the smallest int      for(int i=0; i<testArray.length; i++) {        maximum = max(testArray[i], maximum);      }      return maximum;    }            /** An alternative maxVal() method, faster        int maxVal(int[] testArray)     {      int maximum = Integer.MIN_VALUE; //initialize to the smallest int      for(int i=0; i<testArray.length; i++) {        if (testArray[i] > maximum) {     maximum = testArray[i];        }      }      return maximum;    }        */    
            
             | 
           
            | 
            
            
            
             | 
           
         
         | 
       
     
     | 
   
 
  
    
    
      
        
        
          
            
            fry 
 
        
      
             | 
            
            
            
              
                
                Re: Finding the largest value of an array  
                « Reply #1 on: Oct 31st, 2002, 4:06am » | 
                
                
 
                 | 
               
             
             
            
            and if you really wanna be a weenie, this one is (just slightly) improved:         int maxVal(int[] testArray)      {       // initialize to the first element, since that's      // what will be assigned the first time through      // the loop anyways, in the previous version     int maximum = testArray[0];        // then start the loop at 1 instead of 0, because     // the 0th element has already been 'checked'     for(int i = 1; i < testArray.length; i++) {         if (testArray[i] > maximum) {      maximum = testArray[i];         }       }     return maximum;     } 
            
             | 
           
            | 
            
            
            
             | 
           
         
         | 
       
     
     | 
   
 
 
 |