Java program to search an element in an array


Search an element in an array

Find an element from an array using Linear Searching. Linear searching is a good way to find an element from the array. The array can be of any order, it checks whether a certain element (number , string , etc. ) is in a specified array or not. Basically it is used for small arrays. In the given code, we have allowed the user to enter the numbers to be stored into the arrays. If the element is found we can return the index where the element is located in the array. If the element is not found we can return -1.  



Java version of this program is given bellow :
       
public class Search_Ele {
public static void main(String[] args){
       int[] array={11,-10,25,18,45,55,30,87,-28,18};

       System.out.println("The contents of the Array are :");

       for(int i=0;i<array.length;i++)
          System.out.println("Array[" + i + "] = " + array[i]);

       int search_element=55;
       int find_index=-1;

       for(int j=0;j<(array.length-1);j++){
          if(array[j]==search_element){
             find_index=j;
             break;
          }
       }

       if(find_index!=-1){
          System.out.println(" The search element is : " + search_element);
          System.out.println(" It is found in the array at position : " + find_index);
       }

       else
          System.out.println("\n The search element is not found in the array.");
    }
 }

Popular posts from this blog

The n-queens problem in Java

Convert infix to postfix using stack in Java