Write a C++ program to ask the user to enter the size and elements of an 1D array. Then ask
the user to enter an index and display the element at that index. If user enters a negative
index, then throw a string exception stating an invalid index and display the element at index
0. If the user enters an index greater than the maximum possible index, then throw an integer
exception and display the last possible index along with element at last index. If the user
enters a correct index, then simply display the element at that index.
#include <iostream>
using namespace std;
int main()
{
cout << "Enter the array" << endl;
int n;
cin >> n;
int arr[n];
for (int i=0; i<n; i++) {
cin >> arr[i];
}
while (1) {
cout << "Enter idx of an item" << endl;
int idx;
cin >> idx;
if (idx < 0) {
throw "Negative index exception!";
} else if (idx >= n) {
throw "Index out of bound exception!";
} else {
cout << arr[idx] << endl;
}
}
return 0;
}
Comments
Leave a comment