Java Programming | Searching an Element in Array

Introduction.

This is a tutorial for searching a element in array in Java.  The program is given below that takes the array from user and a number to be found as input and search it and print the position of the element in array. Go enjoy the program. Lets begin…

Program for Searching a Element in Array.

//import Scanner as we require it.
import java.util.Scanner;
 
// the name of our class its public
public class SearchArray {
    //void main
        public static void main (String[] args)
        {
            //declare int
            int a[] = new int[10],no;
            //declare scanner object.
            Scanner input = new Scanner(System.in);
            //a loop to enter elements of array.
            for(int i=0;i<10;i++)
            {
            System.out.println("Enter number:");
            a[i] = input.nextInt();
            }
            //input a number to find.
            System.out.println("Enter the number to be searched:");
            no = input.nextInt();
            //find the number.
            int i;
            for(i=0;i<10;i++)
            {
                if(a[i]==no)
                    break;
            }
            //print the output.
            if(i==10)
                System.out.println("No. not found");
            else
                System.out.println("No. is at "+(i+1)+" Position");
        }
}

Output

Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
Enter number: 6
Enter number: 7
Enter number: 8
Enter number: 9
Enter number: 10
Enter the number to be searched: 9
No. is at 9 Position

How does it work

  1. You enter the array and number to be found.
  2. The number is searched.
  3. The result is printed.

Extending it

The program cannot be extended.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter number.
  5. Declare input as Scanner.
  6. Take the array and and number  and save it in variables.
  7. Add a loop and search the array.
  8. Print the result.

At the end.

You learnt creating the Java program for Searching a Element in Array. So now enjoy the program.

Please comment on the post and share it.


Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: