In: Computer Science
JAVA 6.8 PRACTICE: Loops*: Biggest difference Write a program that outputs the biggest difference (absolute value) between any successive pair of numbers in a list. Such a list might represent daily stock market prices or daily temperatures, so the difference represents the biggest single-day change. The input is the list size, followed by the numbers. If the input is 5 60 63 68 61 59, the output is 7. Hints: Declare a variable for the current number, and another for the previous number. At the start of each loop iteration, set prevNum = currNum, then get the next number into currNum. Maintain a max difference variable. Initialize it with 0. In each loop iteration, check if the difference between currNum and prevNum exceeds maxDiff; if so, update maxDiff with that difference. Don't forget to take the absolute value of the difference before the above comparison. Don't try to check the max difference for the first number in the list, since no previous number exists.
JAVA PROGRAM:
import java.util.*;
public class Test {
// main() function
public static void main(String[] args) {
// Declare Scanner object sc
Scanner sc = new Scanner(System.in);
//Declare a variable for the current number, previous number
int currNum,prevNum;
// Initialize it with 0
int maxDiff = 0;
// Ask the input size of list
System.out.print("Enter input is: ");
int list_size = sc.nextInt();
// Declare the list
int[] list = new int[list_size];
// Ask the user for list element
for(int i=0;i<list_size;i++){
list[i] =sc.nextInt();
}
// for loop iteration,
for(int i=0;i<list_size-1;i++){
// set prevNum = currNum
prevNum = list[i];
//get the next number into currNum
currNum = list[i+1];
// check if the difference (currNum - prevNum) exceeds maxDiff
// take absolute value of the difference using Math.abs() function
if(Math.abs(currNum-prevNum)>maxDiff){
//update maxDiff with that difference
maxDiff = Math.abs(currNum-prevNum);
}
}
// Display the output maxdiff
System.out.println("The output is: "+ maxDiff);
}
}
OUTPUT:
NOTE: If you don't understand any step please tell me.