Java programming /* Method that returns the difference between the largest * and
ID: 3573539 • Letter: J
Question
Java programming
/* Method that returns the difference between the largest
* and smallest elements of an array of doubles
*
*/
public class ArrayDifference
{
public static void main( String [] args )
{
double [] array = { 72.3, 6.7, 12.6, 40.7, 21.8, 49.9 };
System.out.print( "The elements are " );
for ( int i = 0; i < array.length; i++ )
System.out.print( array[i] + " " );
System.out.println( );
System.out.println( "The difference between the largest and "
+ "smallest elements is "
+ largestSmallestDifference( array ) );
}
// Insert your code here
}
Explanation / Answer
/* Method that returns the difference between the largest
* and smallest elements of an array of doubles
*
*/
public class ArrayDifference
{
public static void main( String [] args )
{
double [] array = { 72.3, 6.7, 12.6, 40.7, 21.8, 49.9 };
System.out.print( "The elements are " );
for ( int i = 0; i < array.length; i++ )
System.out.print( array[i] + " " );
System.out.println( );
System.out.println( "The difference between the largest and "
+ "smallest elements is "
+ largestSmallestDifference( array ) );
}
// Insert your code here
//method to calculate the largestSmallestDifference
/**
*
* @param array
* @return difference of largest and smallest
*/
private static double largestSmallestDifference(double[] array) {
// TODO Auto-generated method stub
double largest,smallest, diff = 0;//var to store values
largest=array[0];//assigning largest as 1st element of the array
smallest=array[0];//assigning smallest as 1st element of the array
for(int i=0;i<array.length;i++){
//if the largest is smaller than the current element, then make largest as the current element
if(array[i]>largest){
largest=array[i];
}
//if the smallest is greater than the current element, then make smallest as the current element
if(array[i]<smallest){
smallest=array[i];
}
}
diff=largest-smallest;//calculates the diff
return diff;//returns the diff
}
}
---------------output--------------
The elements are 72.3 6.7 12.6 40.7 21.8 49.9
The difference between the largest and smallest elements is 65.6
-----------------output-------------
Note: feel free to ask question/doubts. God bless you!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.