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

Java: Write a recursive boolean method named isMember. The method should accept

ID: 3923425 • Letter: J

Question

Java:

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 ").

Explanation / Answer

import java.util.Scanner;

/**
* @author
*
*/
public class RecSearch {
   // to place the base condition(exit for recursion)
   static int pos = 0;

   /**
   * @param args
   */
   public static void main(String[] args) {
       int a[];

       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the length of the array:");
       int len = scanner.nextInt();
       a = new int[len];
       for (int i = 0; i < a.length; i++) {
           System.out.print("Enter the Element " + (i + 1) + ":");
           a[i] = scanner.nextInt();
       }

       System.out.print("Enter the number to search for in the array :");
       int numtoSearch = scanner.nextInt();

       System.out.println("Is " + numtoSearch + " is found ?"
               + recursiveSearch(a, numtoSearch));

   }

   /**
   * @param arr
   * @param numtoSearch
   * @return
   */
   public static boolean recursiveSearch(int[] arr, int numtoSearch) {
       if (pos >= arr.length) {
           pos = 0;
           return false;
       }
       if (arr[pos] == numtoSearch)
           return true;
       else {
           pos++;
           return recursiveSearch(arr, numtoSearch);
       }

   }

}

OUTPUT:

Enter the length of the array:8
Enter the Element 1:3
Enter the Element 2:2
Enter the Element 3:6
Enter the Element 4:4
Enter the Element 5:8
Enter the Element 6:9
Enter the Element 7:2
Enter the Element 8:15
Enter the number to search for in the array :6
Is 6 is found ?true

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