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

178 Define a recursive function int findLastInRange(int nums[], int length, int

ID: 3764127 • Letter: 1

Question

178

Define a recursive function
int findLastInRange(int nums[], int length, int minV, int maxV);

Your function should return the index of a value  between minV and maxV, inclusive. Also: since there may be more than one element whose value is in that range, you should return the last one that qualifies.

If there is no such value then your function should return -1.

Array used to test your code: int vals[] = {10, 45, 23, 89, 12, 0, 2, 14, 33, 67, 13, 44};

The inputs are values for minV and maxV.

For example, if minV is 12 and maxV is 15 then you would return 10 (the index of 13 in vals).

Hint: For the recursive case, look at value nums[length-1]. If that's in range, then return length-1.

Otherwise recursively call the function with length-1.

Return -1 for the base case length <= 0.

Explanation / Answer


/**The java program FindLast that calls a recursive function
* findLastInRange in the range of minV and maxV and prints
* the value in the range.
* */
//FindLast.java
public class FindLast
{
   public static void main(String[] args)
   {
       //Create an arrayof vals
       int vals[] = {10, 45, 23, 89, 12, 0, 2, 14, 33, 67, 13, 44};
       //Set minV and maxV values
       int minV=12;
       int maxV=15;
      
       System.out.println("Array elemets ");
       for (int i : vals) {
           System.out.printf("%4d",i);
       }
      
      
       //Call findLastInRange method
       int value=findLastInRange(vals, vals.length-1,minV,maxV);
      
       System.out.println(" The value in the range of "+minV+
               " and "+maxV+" is "+value);
   }

  
  
   /**The method findLastInRange that accepts the integer array,
   * size of array, minV ,maxV and checks the value in the range
   * of minV and maxV and returns value in the range otherwise
   * return -1
   * */
   private static int findLastInRange(int[] vals, int length,
           int minV, int maxV)
   {
      
       //Base condtion
       if(length<0)
           return -1;
       //Otherwise check if check if vals[lenght] vlaue is in range
       //of minV and maxV
       if (vals[length]>minV && vals[length]<maxV)
       {
           //return the value
           return vals[length];          
       }
       else
           //Otherwise call the method recursively with lenght-1
           return findLastInRange(vals, length-1, minV,maxV);
      
   }//end of the method
}

-------------------------------------------------------------

Sample Output:

Array elemets
10 45 23 89 12   0   2 14 33 67 13 44
The value in the range of 12 and 15 is 13

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