To write a Java program to check if a value is present in an Array or not.
- Create an instance of the Scanner with the new keyword.
- Specify the System.in as the argument for the Scanner constructor.
- We create array class object and declare any number of size. like here we declare [5] means pass only 5 element.
- From first for loop we execute multiple time at depend on array size which we declare and store input data in a[i] array.
- From Second for loop we execute multiple time at depend on array size which we declare.
- Here we compare search element with storing element. if it is true then break the loop.
- Inside if condition, k==1 then value is present else not present.
import java.util.Scanner;
public class ValuePresent {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int k = 0;
System.out.println("Enter the number of elements: ");
int n = sc.nextInt();
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.println("Enter the number to be searched:- ");
int p = sc.nextInt();
for (int j = 0; j < n; j++) {
if (p == a[j]) {
k = 1;
break;
}
}
if (k == 1) {
System.out.println("The value "+ p + " is Present");
} else
System.out.println("The value "+ p + " is not Present");
}
}
Output : –
Enter the number of elements:
4
Enter the elements:
1
2
3
4
Enter the number to be searched:-
3
The value 3 is Present