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

Write the C++ DynArray class. Here is a brief description of all of the class fu

ID: 3632109 • Letter: W

Question

Write the C++ DynArray class. Here is a brief description of all of the class functions that your class should include:
• No-argument constructor – initializes a DynArray object to being empty.
• One-argument constructor – uses dynamic memory allocation to obtain a contiguous block of memory for storing n int values, where n is its argument.
• show – displays the nth element in the DynArray. If the DynArray is empty or if n is an invalid index, this function should generate an error message.
• set – will set the nth element in the DynArray to x, where n is the value of its first argument and x is value of its second argument. If the DynArray is empty or if n is an invalid index, this function should generate an error message.
• expand – will take an existing DynArray and expand its size by its argument, s. Hint: To expand a DynArray, allocate a new, larger block of dynamic memory, copy the values from the old DynArray to the new memory, and deallocate the old memory.
• A destructor to deallocate dynamic memory when a DynArray object passes out of scope.

Explanation / Answer

#include <iostream>

using namespace std;

class DynArray

{

public:

//member functions

DynArray();

DynArray(int n);

void show(int n);

void set(int n, int x);

void expand();

~DynArray();

private:

int *arra; //pointer to array

int size; //size of the array

};

//default constructor

DynArray::DynArray()

{

arra = NULL;

size = 0;

}

//argumented constructor

//allocates memory for array with size given as

//parameter

DynArray::DynArray(int n)

{

arra = new int[n];

size = n;

}

//shows element at n

void DynArray::show(int n)

{

if( n >= 0 && n < size)

cout << arra[n] ;

else

cout<<" Invalid Index "<< n<<endl;

}

//sets the element x at the position n

void DynArray::set(int n, int x)

{

if( n >= 0 && n < size)

arra[n] = x;

else

cout<<" Invalid Index "<< n<<endl;

}

//expands the size of array

void DynArray::expand()

{

int *tmp = new int[size];

for(int i = 0; i < size; i++)

tmp[i] = arra[i];

arra = new int[size * 2];

for(int i = 0; i < size; i++)

arra[i] = tmp[i];

size = size *2;

delete [] tmp;

}

//destructor

DynArray::~DynArray()

{

delete [] arra;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote