Write a recursive boolean method named isMember. The method should accept two ar
ID: 3866346 • Letter: W
Question
Write a recursive boolean method named isMember. The method should accept two
arguments: an int array and an int value. The method should return true
if the value is found in the array, or false if the value is not found in
the array.
Demonstrate the method in a program that takes input from the user. First,
the program should prompt the user to enter the length of the array. Then,
it should prompt the user for every member of the array. Then, it should ask
the user for a number to search for in the array, and print whether the
number is a member of the array (either "true" or "false").
The language is Java. Thank you.
Explanation / Answer
import java.util.Scanner;
public class Main {
//Array Index at which programme needs to search in current iteration
public static int currentIdx = 0;
public static boolean isMember(int[] list , int value){
boolean found = false;
if(list.length > currentIdx){
if(list[currentIdx] == value){
found = true;
}
else {
//increment current index
currentIdx++;
//Call "isMemeber" recursively if still element in Array remaining to search
if(list.length > currentIdx){
found = isMember(list, value);
}
}
}
return found;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array");
int size = sc.nextInt();
int list[] = new int[size];
for(int i=0;i<size;i++){//for reading array
System.out.println("enter next element");
list[i]=sc.nextInt();
}
System.out.println("enter value to search");
int value = sc.nextInt();
sc.close();
boolean found = isMember(list, value);
System.out.println("Search result for "+value +" found in list is "+found+"");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.