Take as input N, the size of array. Take N more inputs and store that in an array. Take as input M, a number. Write a recursive function which returns the last index at which M is found in the array and -1 if M is not found anywhere. Print the value returned.
Input Format
Enter a number N and add N more numbers to an array, then enter number M to be searched
Constraints
None
Output Format
Display the last index at which the number M is found
Sample Input
5 3 2 1 2 3 2
Sample Output
3
Solution :
import java.util.*;
public class LastIndex {
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int length=s.nextInt();
int arr[]=new int[length];
for (int i=0; i<arr.length; i++) {
arr[i]=s.nextInt();
}
int m=s.nextInt();
//System.out.print(Arrays.toString(arr));
System.out.println(lastIndex(arr,length-1,m));
s.close();
}
private static int lastIndex(int arr[],int i, int num)
{
if(i<0)
{
return -1;
}
if(arr[i]==num)
{
return i;
}
return lastIndex(arr, i-1, num);
}
}
0 Comments