I am absolutely brain-dead with this homework problem:
Print the absolute value of the smallest-magnitude difference between two consecutive integers.
My code is:
import java.io.NotSerializableException;
import java.util.Scanner;
public class Code {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read input for the test cases
int N = scanner.nextInt();
int[] killme = new int[N];
int[] ints = new int[N];
for (int i = 0; i < N; i++) {
ints[i] = scanner.nextInt();
}
int smallestDifference = Integer.MIN_VALUE;
// Your code here
for (int a = 0; a < N - 1; a++) {
killme[a] = ints[a] - ints[a + 1];
for (int b = 1; b < killme.length; b+=1) {
if(killme[b] < smallestDifference)
smallestDifference = ints[a];
}
}
System.out.println("The smallest difference between consecutive integers is " + Math.abs(smallestDifference));
}
}
Edit: The first issue has been resolved, but I am not receiving the desired outputs. For example when I input the array:
500 400 450 600 1000
I receive the output:
500
But the correct output is
50
>Solution :
Yes you must be running into an infinite loop because of this…
for (int b = 1; b < killme.length; a+=1)
Here you are updating the value of the variable a whereas in the condition you are checking, you are using variable b so variable b is never changed. Thus make the change
for (int b = 1; b < killme.length; b+=1)
Hope this works…
Well I got the answer for your second problem as well… No need of using killme variable. Use this:
int smallestDifference = Math.abs(ints[1] - ints[0]); // Math.abs so that it does not give you negative value...
for(int a = 0; a < N - 1; a++){
smallestDifference = (Math.abs(ints[a] - ints[a+1]) < smallestDifference) ? Math.abs(ints[a] - ints[a+1]) : smallestDifference;
}
This shall work for you…