Java Program to Search an Element in an array

Get an element and find the location of element in array, print -1 if element is not found.

Sample Input 1:

5 5 7 9 3 1 9

Sample Output 1:

2

Sample Input 2:

5 5 7 9 3 1 4

Sample Output 2:

-1

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
			
					
import java.util.*;
class SearchArr
{
  public static void main(String args[])
  {
     int size,i,num,found=0;
     Scanner sc=new Scanner(System.in);
     System.out.println("Enter Size Of Array:");
     size=sc.nextInt();
     int a[]=new int[100];
     System.out.println("Enter The Array Elements:\n");
     for(i=0;i<size;i++)
        {
            a[i]=sc.nextInt();

	}
     System.out.println("Enter The Number You Want To Search:");
     num=sc.nextInt();  
     for(i=0;i<size;i++)
        {
            if(num==a[i])
            {
	          System.out.println("The Position Is:"+i);
		     found=1;
	 	  break;
            }
       }
if(found==0)
	System.out.println("Not Found");

  }
}




			
				
			

Program Explanation

Array is a Collection of data with same type.

1. Get the size of the Array

2. Create a array with the given size (Array has 0 to size-1 index to access every location)









        0                        1                        2                         3              .......             size-2                  size-1


3. Get Inputs for Array (See Previous Problems for detail)

4. Get number to find


In the second For Loop,

i starts at 0, and incremented by 1 after every iteration. iteration stops when i is equal to size.

instruction if(num==a[i]) inside the for loop checks every location whether it has searching number, if found print the index location.

In first iteration it checks a[0]

In second iteration it checks a[1]

In Third iteration it checks a[2]

............

............

In last iteration it checks a[size-1]

if number found in any location, further iterations will be terminated using break statement.

If number not found in any of the location, print "not found".

Comments