icse-promo

Question

Write a program to accept the year of graduation from school as an integer value from the user. Using the Binary Search technique on the sorted array of integers given below, output the message ‘Record exists’ if the value input is located in the array. If not, output the message Record does not exist”.
(1982, 1987, 1993. 1996, 1999, 2003, 2006, 2007, 2009, 2010)

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class program9
{
	public static void main(String[] args)
	{
	    int left=0,right=0,mid=0;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter year of graduation: ");
		int graduation = sc.nextInt();
		int[] years = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
		boolean found = false;
		left = 0;
		right = years.length - 1;
		while (left <= right)
		{
		    mid = (left + right) / 2;
			if (years[mid] == graduation)
			{
				found = true;
				break;
			}
			else if(years[mid] < graduation)
			{
				left = mid + 1;
			}
			else
			{
				right = mid - 1;
			}
		}
		if (found==true)
		{
			System.out.println(graduation+" Record exists");
		}
		else
		{
			System.out.println(graduation+" Record does not exist");
		}
	}
}

				
			

Coding Store

Leave a Reply

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