Q:

Java program to search an item into the array using linear search

belongs to collection: Java Array Programs

0

Java program to search an item into the array using linear search

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create an array of integers then we will search an item into the array using linear search and print position of the item in the array.

The linear searching algorithm is used to find the item in an array, This algorithm consists the checking every item in the array until the required item is found or till the last item is in the array. The linear search algorithm is also known as a sequential algorithm.

Program/Source Code:

The source code to search an item into the array using linear search is given below. The given program is compiled and executed successfully.

// Java program to search an item in an array 
// using linear search

import java.util.Scanner;

public class Main {
  static int linearSearch(int arr[], int item) {
    int cnt = 0;
    int pos = -1;

    for (cnt = 0; cnt < arr.length; cnt++) {
      if (arr[cnt] == item) {
        pos = cnt;
        break;
      }
    }
    return pos;
  }

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

    int i = 0;
    int n = 0;
    int arr[] = new int[5];

    int item = 0;
    int pos = 0;

    System.out.printf("Enter array elements: ");
    for (i = 0; i < arr.length; i++)
      arr[i] = SC.nextInt();

    System.out.printf("Enter item to search: ");
    item = SC.nextInt();

    pos = linearSearch(arr, item);

    if (pos == -1)
      System.out.printf("Item not found.");
    else
      System.out.printf("Item found at index %d.", pos);
  }
}

Output:

Enter array elements: 10 20 30 40 50
Enter item to search: 40
Item found at index 3.

Explanation:

In the above program, we imported the java.util.Scanner package to read the variable's value from the user. And, created a public class Main. It contains two static methods linearSearch() and main().

The linearSearch() method is used to search an item into the array and return the index of the index to the calling method.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to search an item in an array using b... >>
<< Java program to find prime and non-prime numbers i...