Page 409 - CA_Blue( J )_Class10
P. 409
SECTION B
12. Define a class to accept values into an array of double data type of size 20. Accept a double value from user and search in the
array using linear search method. If value is found display message "Found" with its position where it is present in the array.
Otherwise display message ''not found". [2023]
Ans. import java.util.*;
public class Linear_Search
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
double a[] = new double[20];
int l = a.length;
int i = 0;
System.out.println("Enter elements in array: ");
for (i = 0; i < l; i++)
{
a[i] = sc.nextDouble();
}
System.out.print("Enter number to search: ");
double n = sc.nextDouble();
for (i = 0; i < l; i++)
{
if (a[i] == n)
{
break;
}
}
if (i == l)
{
System.out.println("Not found");
}
else
{
System.out.println("Found");
}
}
}
13. Define a class to perform binary search on a list of integers given below, to search for an element input by the user, if it is found
display the element along with its position, otherwise display the message "Search element not found". [2022]
2, 5, 7, 10, 15, 20, 29, 30, 46, 50
Ans. class searchInt {
int x[] = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};
int n;
searchInt(int a) {
n=a;
}
void search() {
int f=0, l=x.length, m;
407
Arrays 407

