Answer to Question #271565 in Java | JSP | JSF for Rajani

Question #271565

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
2021-11-25T20:14:58-0500
public 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
APPROVED BY CLIENTS