Javatpoint Logo
Javatpoint Logo

Farthest from Zero Program in Java

The farthest from zero program in Java is a program that finds the element in an array that is farthest from zero. It can be done by calculating the absolute value of each element in the array and returning the element with the largest absolute value. To achieve this, the program calculates the value of each element in the array. Then returns the element with the largest absolute value.

Problem Statement

Imagine we have an array of numbers, and we want to find the number within that array that is farthest from zero. In other words, we're interested in identifying the number with the largest absolute value.

Implementation

Step 1. The first step is to create an array of numbers. We can include any set of numbers you like.

Step 2. We need to iterate through the array to find the number with the largest absolute value. To do this, we initialize two variables farthestNumber and farthestDistance. These variables will keep track of the farthest number and its distance from zero, respectively. We start with the first number in the array.

Step 3. Next, we loop through the array and calculate the absolute value of each number. If we find a number with a greater absolute value than our current farthestDistance, we update our farthestNumber and farthestDistance variables.Step

FarthestFromZero.java

Output:

The farthest number from zero is: 7.2

Complexity

The time complexity of the above algorithm is O(n), where n is the length of the input array. This is because the algorithm iterates over the array once.

The space complexity of the above algorithm is O(1), as it does not use any additional space.

Conclusion

We have created a Java program to find the number farthest from zero in an array of numbers. The program showcases fundamental concepts of working with arrays and conditional statements in Java.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA