Java Array Program Implement Linear Search Algorithm

By | July 4, 2019

Task: Write a Java Array Program Implement Linear Search Algorithm. Input 10 numbers in array. Input a number to search in the array. Find index of this item in array of 10 integers.

The source code for Linear Search program using array in Java programming Language:

/*
 * Write a Java program to Search an item in array of
10 integers. Use Linear search algorithm
 */
package linearsearchjava;
import java.util.Scanner;
/**
  * @author www.EasyCodeBook.com
 */
public class LinearSearchJava {

    public static void main(String[] args) {
        int a[]=new int[10], i, item, itemIndex=-1;
        Scanner input = new Scanner(System.in);
        for(i=0;i<a.length;i++)
        {
            System.out.print("Enter Number in Array["+i+"]=");
            a[i] = input.nextInt();
        }
            System.out.print("Enter Number to search in Array:");
            item = input.nextInt();
        for(i=0;i<a.length;i++)
            if(a[i]==item)
            {
                itemIndex=i;
                break;
            }
        if(itemIndex==-1)
            System.out.println("Number "+item+" not found in array!");
        else
            System.out.println("Number "+item+" found on index="+i);
    }
    
}

The sample run of the program and output is as shown below:
Enter Number in Array[0]=10
Enter Number in Array[1]=20
Enter Number in Array[2]=30
Enter Number in Array[3]=40
Enter Number in Array[4]=50
Enter Number in Array[5]=60
Enter Number in Array[6]=70
Enter Number in Array[7]=80
Enter Number in Array[8]=90
Enter Number in Array[9]=100
Enter Number to search in Array:70
Number 70 found on index=6

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *