Algorithm
-
Input:
- Accept the array (let's call it
arr
) and the value to be checked (let's call ittarget
).
- Accept the array (let's call it
-
Initialization:
- Initialize a variable (let's call it
found
) to false.
- Initialize a variable (let's call it
-
Loop Through the Array:
- Use a loop (e.g.,
for
orwhile
) to iterate through each element in the array. - For each element, compare it with the target value.
- Use a loop (e.g.,
-
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.
- Set
- If the current element is equal to the target value:
-
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.
- If
- After the loop, check the value of
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
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
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
Four is found.
Demonstration
Java Programing Example to Check if An Array Contains a Given Value-DevsEnv