Posts

Java program to check element is present in array or not - CY

check element is present in array or not - codeYourslf

In this article you can learn 2 different approaches to check whether an element is present in an array or not. Please check both the approaches, to get complete idea.

Hey I will write the code using my mobile phone, please support.

Approach:-1 "check element is present or not in the array using linear search"

 
import java.util.Scanner;
public class usingLlinearSearch {
  public static void main(String[] args) {
    int[] arr = {3,5,7,1,0,6};
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter the element: ");
    int ele = sc.nextInt();
    
    int temp = 0;
    for(int i = 0; i < arr.length; i++)
    {
      if(ele == arr[i])
      {
        System.out.println("Element is present in the array.");
        temp = temp + 1;
        break;
      }
    }
    
    if(temp == 0){
      System.out.println("Element is not present in the array.");
    }
  }
}

Enter the element:
4
Element is not present in the array.


Enter the element:
5
Element is present in the array.

This is explanation part

This is extra part

Approach:-2 "element is present or not in an array using contains(); method"

 
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
public class usingContainMethod {
    public static void main(String[] args){
      Integer[] intArray = new Integer[]{1, 2, 9, 0, 3, 4, 5};
      Scanner sc = new Scanner(System.in);
      
      System.out.println("Enter the element: ");
      int ele = sc.nextInt();
      
      List intList = Arrays.asList(intArray);
      if(intList.contains(ele))
      {
        System.out.println("Element is present in the array.");
      }
      else
      {
        System.out.println("Element is not present in the array.");
      }
    }
}

This is the output section

This is explanation part

This is extra part


Hey please share this article with your friends, as a result they can also get knowledge.
And if you get any doubt please ask in the comment section, I will definitely answer to your questions.
`

Post a Comment

Hey Please 👏, feel free to share your opinion 🌍
© codeYourslf. All rights reserved. Distributed by Pixabin