Need Help on Java H/W. Thanks Here is the code for assignment 7 the code we have
ID: 3842397 • Letter: N
Question
Need Help on Java H/W. Thanks
Here is the code for assignment 7 the code we have to update for this assignment
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
public static int search(int ar[], int key){
for(int i=0; i <ar.Length; i++)
if(ar[i] == key)
return i;
return -1;
}
public static void main(String[] args) {
int arr[] = new int[1000];
Scanner sc = new Scanner(System.in);
Random random = new Random();
for(int i=0; i<1000; i++){
arr[i] = random.nextInt(100)+1;
}
System.out.print("Enter integer to be search: ");
int key = sc.nextInt();
int index = search(arr, key);
if(index == -1){
System.out.println(key+" is not available in array");
}else{
System.out.println(key+" is available at location "+index);
}
}
}
Explanation / Answer
RandomArray.java
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
//This method Search for an element in the array using recursion
public static int search(int ar[], int key, int index) {
if (index == ar.length) {
return -1;
} else if (ar[index] == key) {
return index;
} else {
return search(ar, key,++index);
}
}
public static void main(String[] args) {
int index = 0;
int arr[] = new int[1000];
Scanner sc = new Scanner(System.in);
Random random = new Random();
//generate 1000 random numbers and populate those into an array
for (int i = 0; i < 1000; i++) {
//generate an random number between 1 and 1000
arr[i] = random.nextInt(1000) + 1;
}
System.out.print("Enter integer to be search: ");
int key = sc.nextInt();
//Calling the method to search for an array
index = search(arr, key, index);
if (index == -1) {
System.out.println(key + " is not available in array");
} else {
System.out.println(key + " is available at location " + index);
}
}
}
_____________________
Output#1:
Enter integer to be search: 100
100 is available at location 622
_______________________
Output#2:
Enter integer to be search: 123
123 is not available in array
_______________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.