Write a program that takes as input the size of the array and the elements in the array. The
program then asks the user to enter a particular index and prints the element at that index.
Use exception handling mechanisms to handle the accessing of array beyond the limit. In the
catch block, print "The required element is beyond the array limit".
Input format:
First line contains size of the array, second line contains array elements and third line contains
an array index.
Sample1
Input:
3
20
90
4
2
Output:
4
Sample2
Input:
3
20
90
4
5
Output:
The required element is beyond the array limit
#include <iostream>
#include <stdexcept>
int main() {
int size;
std::cin >> size;
int * array = new int[size];
for(int i = 0; i < size; i++) std::cin >> array[i];
int index;
std::cin >> index;
try {
if(index < 0 || index >= size) {
throw std::out_of_range("The required element is beyond the array limit");
}
std::cout << array[index] << '\n';
}
catch(std::out_of_range& e) {
std::cerr << e.what() << '\n';
}
delete[] array;
return 0;
}
Comments
Leave a comment