codescracker


java

Java Program Linear Search



« Previous Program Next Program »


Linear Search

To search any element present inside the array in Java Programming using linear search technique, you have to use only one for loop to check whether the entered number is found in the list or not as shown in the following program.

Java Programming Code for Linear Search

Following Java program first ask to the user to enter the array size then it will ask to enter the array elements, then it will finally ask to enter a number to be search in the given array to check whether it is present in the array or not, if it is present then the program will show the position of that number present in the array:

/* Java Program Example - Linear Search */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int arr[] = new int[10];
       int i, num, n, c=0, pos=0;
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Array Size : ");
       n = scan.nextInt();
	   
       System.out.print("Enter Array Elements : ");
       for(i=0; i<n; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Enter the Number to be Search...");
       num = scan.nextInt();
	   
       for(i=0; i<n; i++)
       {
           if(arr[i] == num)
           {
               c = 1;
               pos = i+1;
               break;
           }
       }
       if(c == 0)
       {
           System.out.print("Number Not Found..!!");
       }
       else
       {
           System.out.print(num+ " found at position " + pos);
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program linear search

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test