Java program How to sort an array and search an element inside it
Input: Array length followed by array elements and the element to be searched
Output: Searched element position
TEST CASE 1
INPUT
9
7 3 12 0 2 4 5 6 8
2
OUTPUT
4
TEST CASE 2
INPUT
9
2 5 7 8 69 36 24 8 6
12
OUTPUT
Not Found
import java.io.*; import java.util.Scanner; public class temp{ public static void main(String[] args) { int n, x, flag = 0, i = 0; Scanner s = new Scanner(System.in); System.out.print("Enter n number: "); n = s.nextInt(); int a[] = new int[n]; System.out.print("Enter the Arr: "); for(i = 0; i < n; i++) { a[i] = s.nextInt(); } System.out.print("Enter the element to find: "); x = s.nextInt(); for(i = 0; i < n; i++) { if(a[i] == x) { flag = 1; break; } else { flag = 0; } } if(flag == 1) { System.out.println("Searched element position is "+i); } else { System.out.println("Not Found"); } } }
OUTPUT:
INPUT:
Enter n number: 9
Enter the Arr: 7 3 12 0 2 4 5 6 8
Enter the element to find: 2
OUTPUT:
Searched element position is 4
INPUT:
Enter n number: 9
Enter the Arr: 2 5 7 8 69 36 24 8 6
Enter the element to find: 12
OUTPUT:
Not Found
INPUT:
Enter n number: 5
Enter the Arr: 1 2 3 4 5
Enter the element to find: 3
OUTPUT:
Searched element position is 2
INPUT:
Enter n number: 4
Enter the Arr: 45 55 65 45
Enter the element to find: 45
OUTPUT:
Searched element position is 0
Scrshot