0% found this document useful (0 votes)
11 views

Class X - Term 01 - Array Program 09

The document contains a Java program that accepts an array of integers from the user in ascending order. It then accepts a target integer from the user to search for in the array using binary search. The program searches the array and outputs whether the target was found, and if so, at what position.

Uploaded by

Adiii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Class X - Term 01 - Array Program 09

The document contains a Java program that accepts an array of integers from the user in ascending order. It then accepts a target integer from the user to search for in the array using binary search. The program searches the array and outputs whether the target was found, and if so, at what position.

Uploaded by

Adiii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

K.E.

CARMEL GROUP OF SCHOOLS


2021–2022
COMPUTER TERM–01
CLASS–X ARRAY PROGRAM–09

QUESTION
Write a program in Java to accept an array of 'n' elements from the user. Accept an element
from the user to be searched in the array using the Binary Search technique.
(Hint: For performing Binary Search, the elements are accepted in ascending order).
CODE
import java.io.*;
import java.lang.*;
import java.util.*;
class Array9
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the array size : ");
int n = sc.nextInt( );
int arr[] = new int[n];
int l = 0, u= n-1;
int pos = 0;
boolean flag = false;

System.out.println("Enter the array elements in ascending order : ");


for(int i=0; i<arr.length; i++)
{
System.out.print("arr[" + i + "] = ");
arr[i] = sc.nextInt( );
}// end of for

System.out.print("\nEnter the element to be searched : ");


int key= sc.nextInt( );

while(l <= u)
{
int mid = (l + u) / 2;

if(arr[mid] == key)
{
pos = mid + 1;
flag = true;
break;
}// end of if
if(arr[mid] < key)
{
l = mid + 1;
}// end of if

if(arr[mid] > key)


{
u = mid - 1;
}// end of if
}// end of while

if(flag == true)
{
System.out.println("Element " + key + " is present in the array");
System.out.println("Element is present at position " + pos);
}// end of if
else
{
System.out.println("Element " + key + " is not present in the array");
}// end of else
}// end of main
}// end of class
OUTPUT

You might also like