Java program to test if an array contains a specific value( search in array)

import java.util.Scanner;
public class Search {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);

int n=sc.nextInt();
int a[]=new int[n];
int flag=0,key,i,j;
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
key=sc.nextInt();
for( j=0;j<n;j++)
{
if(a[j]==key)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("element found at position"+j);
else
System.out.println("element not found");
}

}
i/p: 6
2 3 4 1 9 8
4
o/p: element found at position 2

No comments:

Post a Comment