Monday, October 5, 2015

linear search program in java

Linear search in java program is used to find a particular element in array with n number of values

Example 

Write a program to find a particular position of element in given dynamic array

Program 

import java.util.Scanner; / this package util and Class Scanner is declared to take input from user
/*
*@ scanner class
* @author khant vyas
*/public class linearsearch // name of class
{

public static void main(String[] args) {
int value,sizea,searchele, list[]; // list variable to array
Scanner sc = new Scanner(System.in); // sc is object to the Scanner class
System.out.println("enter number of elements you need to enter");
value=sc.nextInt(); // nextInt() method is used accept intiger value from user
list=new int[value];// array initilization
System.out.println("enter "+value+" elements ");

for(sizea=0;sizea
list[sizea]=sc.nextInt(); // adding value by user in array of size sizea-1
}
if(sizea==value)
System.out.println("enter the element you wanted to find");
searchele=sc.nextInt();// user enter element to be searched

for(sizea=0;sizea if(list[sizea]==searchele)// comparing  values in array with user entered element 
     {
System.out.println("this" +searchele+" is at position"+(sizea+1));
break;
}
}
if(sizea==value)
       {
System.out.println(searchele+" not in this array");
}
}

}

Output

java linear search output not found
linear search search

No comments:

Post a Comment