Interview Questions from PrepBytes with Answers.
- Badu Blogger

- Jul 14, 2019
- 1 min read

Answer is ::
Program ::
Using Scanner Class :
import java.io.*; //Input Output Package imported
import java.util.*; //Util Package imported
public class PrepBytes1
{
public static void main(String args[])
{
int i,flag; //Required variables are declared
char ch;
Scanner in = new Scanner(System.in); //object of Scanner Class is created
//for taking inputs from User. Present in java.util package.
System.out.println("Enter the Size of an Array ::");
int n = in.nextInt(); //nextInt() method is present in Scanner Class
//used to get Integer values from User.
int A[] = new int[n]; //Array of integer is created of size 'n'
System.out.println("Enter Sorted Array Elements ::");
for(i=0;i<n;i++)
{
A[i]=in.nextInt();
} //Taking Sorted array from user and storing them
//into array.
do
{
System.out.println("Enter the Element to be Searched ::");
int key = in.nextInt();
flag=0; //flag is used as a indicator if the element is
//found or not
for(i=0;i<n;i++)
{
if(key==A[i]) //Comparison is made with key element and
//element stored in array one by one.
{
flag=1; //if found flag is updated to 1 and loop is broken
break;
}
}
if(flag == 1) //result as per flag value is displayed on screen.
{
System.out.println("Element Found");
}
else
{
System.out.println("Element Not Found");
}
System.out.println("Want to Continue (y/n)"); //message to ask whether
//we want to perform same action again is given to console.
ch = in.next().charAt(0);
}while(ch=='y'||ch=='Y');
}
}
Output ::
Enter the Size of an Array ::
5
Enter Sorted Array Elements ::
1
2
3
4
5
Enter the Element to be Searched ::
5
Element Found
Want to Continue (y/n)
y
Enter the Element to be Searched ::
9
Element Not Found
Want to Continue (y/n)
n
Hope u Understood the concept. Happy Learning.

Comments