Program to search an element from an array | Java Programs


 

Code:

import java.util.Scanner;

public class Pr43 {

    public static void main(String[] args) {
        int n;

        System.out.print("Enter size of array: ");
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        int a[] = new int[n];

        for (int i = 0; i < a.length; i++) {
            System.out.print("Enter " + (i + 1) + " element: ");
            a[i] = sc.nextInt();
        }

        System.out.print("\nEnter element which you want to search in array: ");

        int no = sc.nextInt();

        int flag = n + 1;

        for (int j = 0; j < a.length; j++) {
            if (no == a[j]) {
                flag = j;
                System.out.println("Your element is at [" + flag + "] position");
            }
        }
        if (flag == n + 1) {
            System.out.println("Your choice is not proper");
        }
    }   
}

Output:


AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page