Find First And Last Indices Of An Array In Java

import java.util.*;
class my{
void search(int a[],int b){
int first=0,last=0;
for (int i=0;i<10;i++){
if (a[i]==b){
first=i;
break;
}
}
for (int j=0;j<10;j++){
if (a[j]==b)
last=j;
}
if (first==0)
System.out.print("[-1,-1]");
else {
System.out.println("["+first+","+last+"]");
}
}
public static void main(String arsg[]){
Scanner sc=new Scanner(System.in);
my m=new my();
int aa[]=new int[10];
System.out.println("Enter 10 number in assending order");
for (int i =0;i<10;i++){
aa[i]=sc.nextInt();
}
System.out.println("Enter the number to be search");
int s=sc.nextInt();
m.search(aa,s);
}

int s=sc.nextInt();
m.search(aa,s);
}
}


Download the code from here

Comments