Searching number
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science )
import java.util.Scanner;
class FindPosition {
public static void main(String[ ] args) {
Scanner sc = new Scanner(System.in);
int num, size;
System.out.print("Enter the size of the array: ");
size = sc.nextInt();
int []arr = new int[size];
System.out.println("Enter " + size + " Elements: ");
for (int i=0; i < size; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Given Array: ");
for (int i=0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.print("\nEnter the number to search in the array: ");
num = sc.nextInt();
for (int i=0; i < size; i++) {
if (num == arr[i]) {
System.out.println(num + " found at position: " + (i+1));
return;
}
}
System.out.println(num + " not found in this Array!");
}
}
OUTPUT
cmd-> javac FindPosition.java
cmd-> java FindPosition
Enter the size of the array: 6
Enter 6 Elements:
45
65
12
10
02
45
Given Array: 45 65 12 10 2 45
Enter the number to search in the array: 10
10 found at position: 4
Enter the size of the array: 8
Enter 8 Elements:
10
21
54
87
98
88
65
12
Given Array: 10 21 54 87 98 88 65 12
Enter the number to search in the array: 22
22 not found in this Array!