Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 22: Write a Java program to search a number in an array and return its index number and if the element is not found in the array return (-1).

ArraySearch.java

import java.util.Scanner;

public class ArraySearch
{
	public static void main(String[] args)
	{
		int n;
		
		Scanner s = new Scanner(System.in);
		
		System.out.println("Enter the number of elements to be included in the array");
		n=s.nextInt();
	
		//Input Elements in array
		
		int a[] = new int[n];
		System.out.println("Enter elements of array");
		for(int i=0; i < n; i++)
		{
			System.out.print("Enter "+(i+1)+" element: ");
			a[i]=s.nextInt();	
		}
		
		System.out.println("Enter the element to be searched in the array");
		int element = s.nextInt();
		int i;

		for(i=0;i < n;i++)
		{
			if(a[i]==element)
			{
				System.out.println("Element "+element+" found at index no. "+i);
				return;
			}
		}

		if(i==n)
		{
			System.out.println("Element cannot be found in the array");
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.