I have been reviewing arrays for an exam. What better way than to solve array exercises.Â This is one of the many that I’ve finished. Elementary, you might think, but I’ve been out of this kind of programming for a while.

For this exercise, it’s about looking for the number closest to zero. Since the original problem (the first 3 lines commented) doesn’t state any other conditions like, *“in case there is more than one number closest to zero, return the first element found that is closest” *or *“check an element in the array with a value of zero then stop”*, let’s leave that off for another solution. I won’t be using Math functions in Java too since that would defeat the purpose of the exercise.

Feel free to comment for a simpler answer or if there are mistakes in the solution.

/*

Complete the following program so that it computes and writes out the element in the array that is closest to zero.

*/

class ClosestToZero

{public static void main ( String[] args )Â {

// test data

int[] data = {3, 5, -2, 7, 4, 12, -3, 2, 8, -5};

// declare and initialize variables

int curr = 0; // Just a variable to hold the square of the current index in the loop

int near = data[0]; // Current closest to zero. Assume it’s first element of the array in the beginning.// find the element nearest to zero

for ( int index=0; index < data.length; index++ ) {

curr = data[index] * data[index]; // We square the values to eliminate negative numbers

System.out.print( currÂ + ” or “ + near + “? “ );

if ( curr <= (near * near) )Â { // What happens if we just use ‘<‘ instead of ‘<=’ ?

near = data[index];

} System.out.println( near );

}

// write out the element closest to zero

System.out.println( near );}

}

Output of the program:

3 or 3? 3

5 or 3? 3

-2 or 3? -2

7 or -2? -2

4 or -2? -2

12 or -2? -2

-3 or -2? -2

2 or -2? 2

8 or 2? 2

-5 or 2? 2

Closest to zero: 2

The number closest to zero (in terms of distance) is always the number with the least value. True? YES and NO.

NO because, -2 is less than 2. However, both are of the same distance to zero.

Since this is about distance not direction, let’s get rid of negative values.Â Square the value to get a positive number in case there are negative numbers in the array. Absolute would have been the choice but no Math functions.

So YES, if we take the absolute value of each number, the number closest to zero is the one with the least value in the array.

### Similar Posts:

- > Assigning Numbers to Groups – Problem #2: Distribute 1 Per Group or Even/Odd November 4, 2020
- > shared nothing October 3, 2006
- > “PROGRAM_NAME” Is Not Recognized As An Internal Or External Command, Operable Program Or Batch File December 20, 2013
- > A Theory On The RNG Factor In WOW May 22, 2009
- > get values of multiple input elements from a form February 4, 2007