Please click on ads

Please click on ads

Wednesday, 6 January 2021

linear search in java

 import java.util.Scanner;

public class Test3 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

int flag=0;

int a[]= new int[10];

System.out.print("enter the elements of array");

for (int i=0; i<a.length;i++)

{

a[i]=s.nextInt(); 

}System.out.print("enter the element that need to besearched");

int search=s.nextInt();//5

int count=0;for (int i=0; i<a.length;i++)// 7 1 1 5 6 8 2 1 9

{

if (a[i]==search)//7==5{//System.out.print("The element " +search + "is present at position "+ (i+1));count=count+1;flag=1;}}if (flag==0)System.out.print("The element not found");elseSystem.out.print("The element " + search +"appears "+ count +" times");}}

No comments:

Post a Comment