Java Program to search Given Number in an Array

If you want to find particular element in an array we can serve this purpose by using this program.Where User defined element is compared with all the element present in the array.Suppose if element is present,resultant output will be element present at location ‘i’,if element is not present resultant output will element is not present in the array.

We will be taking two example for this topic. In Example-1 we will take static inputs. And in Example-2 we will be talking user defined inputs.

Example 1: Using Static Inputs

Algorithm/Program Explanation

  1. Start
  2. Define and initialize Array
    • int array[]={data};
  3. Define integer variable
    • int element=10// number to be searched
    • int count=0// to increase the counter value
  4. Define for loop
    • for(int i=0;i<array.length;i++)
    • check for condition
    • if(array[i]==element)
      • print element is present at location ‘i’.
      • count=count+1;
      • break
    • check for condition
    • if(count==0)
      • print element is not found
  5. End
/*
Java Program to find  Given Element in the Array*/
import java.util.*;
class SerachaArray{
 public static void main(String args[]){
  int array[]={1,2,3,4,5,6,7,8,9,10};
  int element=10,count=0;
  int i;
  for(i=0;i<array.length;i++){
   if(array[i]==element){
    System.out.println("Element "+ element + " is Found at location-"+ i);
    count=count+1;
    break;

   }
  }
  if(count==0){
   System.out.println("Element is Not Found");
  }
 }

}
Element 10 is Found at location-9

Eaxmple-2 Taking User Defined Inputs

/*
Java Program to find  Given Element in the Array*/
import java.util.*;
import java.util.Scanner;
class SearchArray{
 public static void main(String args[]){
  int count=0;
  int array[]=new int[100];
  int size;
  System.out.println("Enter The Size of Array");
  Scanner sc=new Scanner(System.in);
  size=sc.nextInt();
  System.out.println("Enter All Elements in The arrays");
  for(int i=0;i<size;i++){
   array[i]=sc.nextInt();
  }
  System.out.println("Enter the Element to be Searched:");
  int i ,element;
  element=sc.nextInt();
  for(i=0;i<array.length;i++){
   if(array[i]==element){
    System.out.println("Element "+ element + " is Found at location-"+ i);
    count=count+1;
    break;

   }
  }
  if(count==0){
   System.out.println("Element is Not Found");
  }
 }

}
Output:
Enter The Size of Array
10
Enter All Elements in The arrays
1 2 3  4 5 6 7  8 9 10
Enter the Element to be Searched:
10
Element 10 is Found at location-9

Question asked in this Topic

  • Code Java Program to Search Given element in the Array?
  • Write a logic to Search User Specified Element in the Array?
  • WAP to Take user defined array, take input for element and search whether element is present in the array or not?
  • Given an integer Array check whether Number 10 is present in array or not?

Related Topics:

Leave a Comment