JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not.

JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not.


import java.util.*;
class Arraysearch
{
    public static void main()
    {
        Scanner Sc=new Scanner(System.in);
        System.out.println("Enter array size: ");
            int n=Sc.nextInt();
            int num[]=new int[n];
        for(int i=0;i<n;i++)
        {
            System.out.println("Enter element: ");
            num[i]=Sc.nextInt();
        }
        for(int i=0;i<num.length;i++)
        {
            for(int j=0;j<num.length-1;j++)
            {
                if(num[j]>num[j+1])
                {
                    int t=num[j];
                    num[j]=num[j+1];
                    num[j+1]=t;
                }
            }
        }
        for(int i=0;i<num.length;i++)
        {
            System.out.print(num[i]+" ");
        }
        System.out.println(" ");
        System.out.println("Enter check: ");
        int val=Sc.nextInt();

        int x=n-1;
        int s=0;int f=0;int m=0;

        while(s<=x)
        {
            m=(s+x)/2;
            if(val==num[m])
            {
                f=1;
                break;
            }
            else if(num[m]>val)
            {
                x=m-1;
            }
            else
            {
                s=m+1;
            }
        }
        if(f==1)
        {  System.out.println("Found in the list, search successful and the index of the searched number(val) is "+m);   }
        else if(f==0)
        {   System.out.println(" Not found in the list, search unsuccessful.Entered number "+val+" is not found");         }   }   }


JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not. 
JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not.
Output:-    
Enter array size:
5
Enter element:
1
Enter element:
2
Enter element:
3
Enter element:
4
Enter element:
5
1 2 3 4 5 
Enter check:
5
Found in the list, search successful and the index of the searched number(val) is 4 

JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not.


JAVA program to define the size of an array, take input its elements, display the array, take input a number and check whether it is present in the array or not.

No comments:

Powered by Blogger.