Answer to Question #193345 in C++ for Sivasurya

Question #193345

Define a class Array which can hold 5 elements of type int. Define a member function int Get(int index); which returns the indexth element of the array if index is between 0 to 4 and throws an exception if index is out of bounds. Catch the exception in the main program and print an error


1
Expert's answer
2021-05-16T00:29:25-0400
#include <iostream>
#include <string>


using namespace std;




class Array {
private:
	//array to hold 5 elements of type int
	int elements[5];
public:	
	Array(){}	
	Array(int elements[]){
		for(int i=0;i<5;i++){
			this->elements[i]=elements[i];
		}
	}	
	~Array(){}
	// Define a member function int Get(int index); 
	int Get(int index){
		//if index is between 0 to 4 and throws an exception if index is out of bounds.
		if(index<0 || index>=5){
			throw exception("Index is out of bounds."); 
		}
		return elements[index];
	}
};


int main(){
	//Catch the exception in the main program and print an error
	try {
		int elements[]={5,4,8,6,3};
		Array _array(elements);
		cout<<_array.Get(2)<<"\n";
		cout<<_array.Get(4)<<"\n";
		cout<<_array.Get(10)<<"\n";
	}
	catch (exception& exp) {
		cout<<exp.what()<<"\n";
	}
	system("pause");
	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