Answer to Question #182267 in C++ for Mani

Question #182267

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


1
Expert's answer
2021-04-16T15:40:14-0400
#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;
}

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