Array-promo

Question

Search an element in an array.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					
 
  import java.util.Scanner;
public class searchElementInAnArray
{  
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr1;
        boolean elementfound=false;
        int n=0,i=0,item=0,pos=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a no. of elements in the array");   
        n = sc.nextInt(); 
        System.out.println("Enter numbers in array");
        arr1=new int[n];
        for(i=0;i< n;i++)
        {
            arr1[i]=sc.nextInt();
        }
        System.out.println("Enter element to be searched in an array");
        item=sc.nextInt();
          
        System.out.println();  
          
        
        for ( i = 0; i < n; i++) 
        {   
            if(arr1[i]==item)
            {
                elementfound=true;
                pos=i;
                break;
            }
        } 
        if(elementfound==true)
        {
            System.out.println(item+" found in the array at position "+pos); 

        }
        else
        {
            System.out.println(item+" not  found in the array."); 
        }
    }  
}     

				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

Your email address will not be published. Required fields are marked *