Write a program to check whether the indexes given are valid index are not. Print "Out of Bounds" if any attempt is made to refer to an element whose index is beyond the array size , else print the element present at the index.
Input Format
The first lineof input contains n , denoting the sizeof array.
The second line contains n spaced integers , denoting elementsof array
The third line contains q, denoting numberof queries
Next q lines contains an integer, index, whichis to be tested.
Output Format
Foreach queryprint the value atindexif theindex is a validindex ,elseprint "Out of Bounds".
Sample Input
10 // Size of array
1 2 3 4 5 6 7 8 9 10 // array elements
2 // No. Of Queries
4 // index to be retrieved
13 // index to be retrieved
Sample Output
5
Outof Bounds
import java.util.*;
// Do NOT change the class name
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([System.in](<http://system.in/>));
try {
int size = sc.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
// Fill the ArrayList with input values
for (int i = 0; i < size; i++) {
int x = sc.nextInt();
arr.add(x); // Use add to insert elements into ArrayList
}
int quer = sc.nextInt();
int[] queries = new int[quer];
// Fill the queries array
for (int i = 0; i < quer; i++) {
queries[i] = sc.nextInt();
}
// For each query, print the element at the specified index if it exists
for (int i = 0; i < quer; i++) {
int queryIndex = queries[i];
if (queryIndex >= 0 && queryIndex < arr.size()) {
System.out.println(arr.get(queryIndex)); // Print element at queried index
} else {
System.out.println("Out of Bounds"); // Handle out of bounds query
}
}
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}