Q:

Write a Java Program to Search Key Elements in an Array

belongs to collection: Array Programs in Java with Examples

0

Write a Java Program to Search Key Elements in an Array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.Scanner;
public class Javaexcercise
{
    public static void main(String[] args) 
    {
        int num, x, flag = 0, i = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter no. of elements you want in array:");
        num = s.nextInt();
        int a[] = new int[num];
        System.out.println("Enter all the elements:");
        for(i = 0; i < num; i++)
        {
            a[i] = s.nextInt();
        }
        System.out.print("Enter the element you want to find:");
        x = s.nextInt();
        for(i = 0; i < num; i++)
        {
            if(a[i] == x)
            {
                flag = 1;
                break;
            }
            else
            {
                flag = 0;
            }
        }
        if(flag == 1)
        {
            System.out.println("Element found at position:"+(i + 1));
        }
        else
        {
            System.out.println("Element not found");
        }
    }
}

Result:

Enter no. of elements you want in array: 5

Enter all the elements:

10

20

30

40

50

Enter the element you want to find: 20

Element found at position: 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Array Programs in Java with Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java Program to Accept the Marks of a Stud... >>
<< Write a Java Program to Display Transpose Matrix...