Answer to Question #288514 in Java | JSP | JSF for Kudu

Question #288514

you have been an integer array A of size N.you need to pfint the number with the value closest to zero.if there are multiple elements print the number with greater value.




1
Expert's answer
2022-01-18T17:22:58-0500
class Main {

    public static void main(String[] args) {
        int[] A = {-2, 5, 2, -1, 3, -4, 1, -5};
        int closest = Integer.MAX_VALUE;
        for (int i = 0; i < A.length; i++) {
            if (Math.abs(A[i]) < Math.abs(closest)) {
                closest = A[i];
            } else if (Math.abs(A[i]) == Math.abs(closest) && A[i] > closest) {
                closest = A[i];
            }
        }
        System.out.println(closest);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog