Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Recall that in C++ there is no check on an array index out of bounds. However, d

ID: 3769811 • Letter: R

Question

Recall that in C++ there is no check on an array index out of bounds. However, during program execution, an array index out of bounds can cause serious problems. Also, in C++ the array index starts at 0.

Design and implement the class myArray that solves the array index out of bound problem, and also allow the user to begin the array index starting at any integer, positive or negative. Every object of the type myArray is an array of the type int. During execution, when accessing an array component, if the index is out of bounds, the program must terminate with an appropriate error message. Consider the following statements:



myArray list (5); // Line 1

myArray myList (2,13); // Line 2

myArray yourList (-5,9); // Line 3



The statement in Line 1 declares list to be an array of 5 components, the component type is int, and the components are: list[0], list[1], …, list[4]; the statement in Line 2 declares mylist to be an array of 11 components, the component type is int, and the components are myList[2], myList[3], …., myList[12]; the statement in Line 3 declares yourList to be an array of 14 components, the component type is int, and the components are: yourList[-5], yourList[-4], …., yourList[0], …., yourList[8]. Write a program to test the class myArray.

Explanation / Answer

Hi,

Below is the program you are looking for:

Program:

#include <iostream>
using namespace std;

//Designing my array class
class myArray {
public:
myArray(int num) {
start_value = 0;
end_value = num-1;
array = new int[num];
for (int i=0; i<num; i++) array[i] = i + 1;
}
myArray(int num, int m) {
start_value = num;
end_value = m - 1;
array = new int[m-num];
for (int i=0; i<m-num; i++) array[i] = start_value + i;
}
int operator[](int index_value);
private:
int start_value;
int end_value;
int *array;
};

int myArray::operator[](int index_value) {
if (index_value>=start_value && index_value<=end_value) {
return (array[index_value-start_value]);
}
cout << "Error: Array Index out of bound" << endl;
exit(1);
}

int main()
{
//Input the list value to be tested
myArray list(5);
myArray myList(2,13);
myArray yourList(-5,9);
int i;

cout << "Elements from list are : " <<endl;
for (i=0; i<5; i++) cout << list[i] << " ";
cout << endl;
cout << "Elements from myList are: ";
for (i=2; i<13; i++) cout << myList[i] << " ";
cout << endl;
cout << "Elements from yourList are : ";
for (i=-5; i<9; i++) cout << yourList[i] << " ";
cout << endl;

cout << " Now Accessing list(6): " << endl;
cout << list[6];
system("PAUSE");

return 0;
}

Hope that helps...HAPPY ANSWERING!!!!!!!!!!!!!