Algorithm


  1. Input:

    • Accept the array (let's call it arr) and the value to be checked (let's call it target).
  2. Initialization:

    • Initialize a variable (let's call it found) to false.
  3. Loop Through the Array:

    • Use a loop (e.g., for or while) to iterate through each element in the array.
    • For each element, compare it with the target value.
  4. Check for Match:

    • If the current element is equal to the target value:
      • Set found to true.
      • Break out of the loop since there is no need to continue searching.
  5. Output:

    • After the loop, check the value of found.
      • If found is true, print or return a message indicating that the array contains the target value.
      • If found is still false, print or return a message indicating that the array does not contain the target value.

 

Code Examples

#1 Code Example- Check if Int Array contains a given value

Code - Java Programming

class Main {
  public static void main(String[] args) {

    int[] num = {1, 2, 3, 4, 5};
    int toFind = 3;
    boolean found = false;

    for (int n : num) {
      if (n == toFind) {
        found = true;
        break;
      }
    }
    
    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
3 is found.

#2 Code Example- Check if an array contains the given value using Stream

Code - Java Programming

import java.util.stream.IntStream;

class Main {
  public static void main(String[] args) {
    
    int[] num = {1, 2, 3, 4, 5};
    int toFind = 7;

    boolean found = IntStream.of(num).anyMatch(n -> n == toFind);

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
      
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
7 is not found.

#3 Code Example- Check if an array contains a given value for non-primitive types

Code - Java Programming

import java.util.Arrays;

class Main {
  public static void main(String[] args){

    String[] strings = {"One","Two","Three","Four","Five"};
    String toFind= "Four";

    boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind));

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Four is found.
Advertisements

Demonstration


Java Programing Example to Check if An Array Contains a Given Value-DevsEnv