Create a program that prompts the user for an integer number and searches for it within an array of 10 elements. What is the average number of comparisons required to find an element in the array? in java
Answer 1:
Code Screenshot :
Executable Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//Scanner for user
input
Scanner scan = new
Scanner(System.in);
//Declaring an integer
array with 10 elements
int[] intArray = new int[]{
1,2,3,4,5,6,7,8,9,10 };
//Prompting the user for
input
System.out.print("Enter any number
to search in the array: ");
int number = scan.nextInt();
//Looping through the
array
for(int i =0;i<10;i++){
//checking if number exists in array
if(intArray[i]
== number){
//Print the result with index
position
System.out.println(number + " found at index
position " + (i+1));
//Exit if found
System.exit(0);
}
}
//Print if element not
found
System.out.println("Element not
found.");
}
}
Sample Output :
Answer 2:
Linear Search
The average number of comparisons to find an element in the array is (n+1)/2 , where n is the number of elements.
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)
Get Answers For Free
Most questions answered within 1 hours.