- for the size of array
- for array
- Number to search in array
In this program loop will go upto the value of n-1 or i<n then m is compared to value of arr[i] if the value is in array then it return the value of i else -1;
5
11 12 13 14 15
14
Sample Output 1
3
Sample Input 2
3
1 4 6
4
Sample Output 2
1
Program
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
int m=sc.nextInt();
System.out.println(linearsearch(arr, m));
}
public static int linearsearch(int []arr,int m)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i]==m)
{
return i;
}
}
return -1;
}
}