Find Difference Between Smallest and Largest Elements in an Array

The following code shows how to Find Difference Between Smallest and Largest Elements in an Array in Java.

public class Main
{
	public static void main(String[] args) {
	    System.out.println("Array created by initialization...");
	    int[] myarray={67, 12, 97, 33, 58};
	    for(int i=0;i<myarray.length;i++)
	        System.out.println(myarray[i]);
	    int smallest=myarray[0];
	    int largest=myarray[0];
	    for(int i=0;i<myarray.length;i++)
	    {
	       if(myarray[i]<smallest)
	            smallest=myarray[i];
	       if(myarray[i]>largest)
	            largest=myarray[i];
	    }
		System.out.println("Smallest element in the array = "+smallest);
		System.out.println("Largest element in the array = "+largest);
		System.out.println("Difference between smallest and Largest element  = "+(largest-smallest));
	}
}

Output

Array created by initialization…
67
12
97
33
58
Smallest element in the array = 12
Largest element in the array = 97
Difference between smallest and Largest element = 85


Further Reading

Java Practice Exercise

programmingempire