Answer to Question #212680 in C++ for champu

Question #212680

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.


1
Expert's answer
2021-07-01T15:30:46-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS