Searching Element of Array in Java:
Here we will create first an Array of Number ,then we will input a number
and check that number is present in array or not if present then it will print
with it's location in Array.
- Array = [1, 2, 3, 4, 5]
- Input = 2
- Output = Number is Found At Position 1.
Code :
import java.util.Scanner;
import java.util.Arrays;
public class SearchArray {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int num,p=0;
boolean find = false;
int[] arr = new int[5];
String str;
System.out.println("Enter the value of arr:");
for(int i=0;i<arr.length;i++){
arr[i] = scan.nextInt();
}
str = Arrays.toString(arr);
System.out.println(str);
System.out.println("Enter the number you want to check");
num = scan.nextInt();
for(int j =0;j<arr.length;j++) {
if (arr[j] == num) {
find = true;
p=j;
}
}
if(find){
System.out.println("Number is Found At Position ="+p);
}
else{
System.out.println("Number is not Found");
}
}
}
Click on Image For Program View
🙏THANKS FOR VISIT🙏
Searching Element of Array in Java- CodexRitik
Reviewed by CodexRitik
on
July 29, 2020
Rating:
No comments: