Java Program to Search an Element in an Array using Linear Search

  • Write a Java program to search an element in an array using linear search algorithm.

Given an array of integer size N and a number K. We have to search number K in given array. If number K is present in input array then we have to print it's index.

Algorithm to search an element in an unsorted array using linear search
Let inputArray is an integer array having N elements and K be the number to search.
  • Using a for loop, we will traverse inputArray from index 0 to N-1.
  • For every element inputArray[i], we will compare it with K for equality. If equal we will print the index of in inputArray.
  • If even after full traversal of inputArray, non of the element matches with K then K is not present in inputArray.

Java program to search an element in an array

package com.tcc.java.programs;

import java.util.*;

public class ArrayLinearSearch {
    public static void main(String args[]) {
        int count, num, i;
        int[] inputArray = new int[500];
  
        Scanner in = new Scanner(System.in);
  
        System.out.println("Enter number of elements");
        count = in.nextInt();
        System.out.println("Enter " + count + " elements");
        for(i = 0; i < count; i++) {
            inputArray[i] = in.nextInt();
        }

        System.out.println("Enter element to search");
        num = in.nextInt();
        // Compare each element of array with num
        for (i = 0; i < count ; i++) {
            if(num == inputArray[i]){
               System.out.println(num+" is present at index "+i);
               break;
            }
        }
  
        if(i == count)
           System.out.println(num + " not present in input array");
    }
}
Output
Enter number of elements
6
Enter 6 elements
3 8 7 2 9 4
Enter element to search
7
7 is present at index 2
Enter number of elements
7
Enter 7 elements
3 8 12 8 11 0 -4
Enter element to search
5
5 not present in input array

Recommended Posts
Java Program to Merge Two Sorted Arrays
Java Program to Find Sum of Elements of an Array
Java Program to Find Average of all Array Elements
Java Program to Find Duplicate Elements in an Array
Java Program to Find Largest and Smallest Number in an Array
Java Program to Insert an Element in Array at Given Position
Java Program to Print Pascal Triangle
Java Program to Print Right Triangle Star Pattern
Java Program to Delete All Spaces from a String
Java Program to Find Count of Each Character in a String
Java Program to Count Words in a Sentence
All Java Programs