Write a program to find closest number to the given number?

In this program we created one method and pass array input and target value.we iterate input number from for loop and compare this number from target value.

				
					public class FindNearestNumber {
	public static int NearestNumber(int arr[], int target) {
		int id = 0;
		int dt = Math.abs(arr[0] - target);
		System.out.println(dt);
		for (int i = 1; i < arr.length; i++) {
			int cd = Math.abs(arr[i] - target);
			System.out.println(cd);
			if (cd < dt) {
				id = i;
				dt = cd;
			}
		}
		return arr[id];
	}

	public static void main(String[] args) {
		int a[] = new int[] { 2, 5, 6, 7, 8, 8, 9 };
		int target = 11;
		System.out.println("Nearest Number is:- " + NearestNumber(a, target));
	}
}
				
			

Output :-
Nearest Number is:- 9

Leave a Comment

Your email address will not be published. Required fields are marked *