Write a program to search an element in an array


This is a Java program that prompts the user to enter an array of integers, and then searches for a specific element in the array. Here is a brief explanation of what the program does:

  • The program first prompts the user to enter the size of the array.
  • It then creates an integer array of the specified size.
  • The program then prompts the user to enter each element of the array.
  • After the user has entered all the elements, the program prompts the user to enter the element they want to search for.
  • The program then loops through each element of the array, comparing it to the search element.
  • If the search element is found in the array, the program sets a flag variable (f) to 1 and breaks out of the loop.
  • If the search element is not found in the array, the flag variable remains 0.
  • If the flag variable is 1, the program displays the position and index of the element in the array. Otherwise, it displays a message indicating that the element was not found.

Note: This program assumes that the user will enter valid input (i.e., integer values for the array size and elements). If the user enters invalid input (e.g., a non-integer value), the program will terminate with an error message.

Source Code

import java.util.Scanner;
class Array_Search_Element
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		System.out.print("Enter the Search Array Element :");
		int s =input.nextInt();
		int i,f=0;
		for(i=0; i<l; i++)
		{
			if(a[i]==s)
			{				
				f=1;
				break;
			}
		}
		if(f==1)
		{
			System.out.printf("The Element is found in the position : %d", i + 1);
			System.out.printf("\nThe Element is found in the index : %d", i);
		}
		else
		{
			System.out.println("The Element is Not found");
		}
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :10
Element of a[1] :20
Element of a[2] :30
Element of a[3] :40
Element of a[4] :50
Enter the Search Array Element :30
The Element is found in the position : 3
The Element is found in the index : 2

Example Programs