How to get the difference between the largest and smallest values in an array of integers in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int array[] = {2, 4, 9, 8, 3, 5, 6};  
        
        int max = array[0];
	    int min = array[0];
	    
    	for (int i = 1; i < array.length; i++) {
    		if (array[i] > max)
    			max = array[i];
    		else if(array[i] < min)
    			min = array[i];
    	}
    	
    	System.out.println("max = " + max);	
    	System.out.println("min = " + min);	
    	System.out.println("max - min = " + (max - min));	
    }
}






/*
run:
 
max = 9
min = 2
max - min = 7
 
*/

 



answered Aug 20, 2021 by avibootz
...