Java Program to Check whether Given Element is Present in Array or not

In previous tutorial we learnt how to accept and print array elements. In this post we will learn is given element is present in array or not, Java program to check whether given element is present in array or not.


  Step by step logic of the given program:


1. Declare and Initialize array and other variables.

2. Input value from user and store it in variable say value.

System.out.println("Enter the value you want to find: ");
int value = obj.nextInt();

3. Run a loop from 0 to arr.length-1(In below program it will run from 0 to 7) because in below program array length is 8.

4. Inside the for loop use one if condition to check whether given value and array value is same or not, if value is same then increment count by one and break the loop. 

for(i=0; i<arr.length;i++) {
	if(arr[i]==value) {
		count++;
		break;
	}
}

5. Outside the loop use one if condition to check whether the count is greater than zero or not, if true then print value is present in array otherwise print value is not present.



  Java Program to Check whether Given Element is Present in Array or not:





import java.util.Scanner;

public class SearchArrayElement {

	public static void main(String[] args) {
		//Array Initialization
		int arr[] = {5,8,2,4,1,9,3,7};
		int count=0,i;
		
		Scanner obj = new Scanner(System.in);
		//Accept value from user to check whether it is present or not
		System.out.println("Enter the value you want to find: ");
		int value = obj.nextInt();
		//Run a for loop
		for(i=0; i<arr.length;i++) {
			if(arr[i]==value) {
				count++;
				break;
			}
		}
		//If count is greater than zero means value is present
		if(count>0) {
			System.out.println("Value is present in array at position : "+(++i));
		}else {
			System.out.println("Given value is not present in array");
		}
	}

}

In above program we have used length attribute to find length of array.


  Same Above Program using for-each loop:


import java.util.Scanner;

public class SearchArrayElement {

	public static void main(String[] args) {
		//Array Initialization
		int arr[] = {5,8,2,4,1,9,3,7};
		int count=0,i=0;
		
		Scanner obj = new Scanner(System.in);
		//Accept value from user to check whether it is present or not
		System.out.println("Enter the value you want to find: ");
		int value = obj.nextInt();
		//Run for-each loop
		for(int ele:arr) {
			i++;
			if(ele==value) {
				count++;
				break;
			}
		}
		//If count is greater than zero means value is present
		if(count>0) {
			System.out.println("Value is present in array at position : "+i);
		}else {
			System.out.println("Given value is not present in array");
		}
	}

}


Output:

Enter the value you want to find : 
1
Value is present in array at position : 5


No comments:

Post a Comment

If you have any doubts, please discuss here...👇