Thursday, 25 January 2018

Write a Java Program to find element using Linear Search

package com.tutorial4u;

import java.util.Scanner;

public class LinearSearch {
     public static void main(String[] args) {
           int num, search,i;
           System.out.print("Enter number of element : ");
           Scanner sc = new Scanner(System.in);
           num = sc.nextInt();
           int array[] = new int[num];
           System.out.println("Enter "+num+ " Element :- ");
           for(i =0 ; i<num;i++){
                array[i] = sc.nextInt();
           }
           System.out.print("Enter Element to find : ");
           search = sc.nextInt();
           for(i = 0;i<num;i++){
                if(search == array[i]){
                      System.out.println("Element "+search+" is present at location "+(i+1));
                      break;
                }
           }
           if(i==num){
                System.out.println("Enter Element is not found");
           }
     }

}


Output :

Enter number of element : 4
Enter 4 Element :-
12
13
15
17
Enter Element to find : 15
Element 15 is present at location 3

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...