Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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);
}
}
}

Task 1: Update code from Assignment 7 se only recursion to solve the problem Do not use a for loop!! Create an array that holds 1000 random integers between 1-1000 Allow the user to enter an integer to search Output the location of number if it exists in the Array. (Number could appear more than once.) or Output number does not exist in the Array

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote