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

randomly add 1-13 4 times in an int stack dynamic array here\'s the stack file #

ID: 3902605 • Letter: R

Question

randomly add 1-13 4 times in an int stack dynamic array here's the stack file

#include "stack.h"

using namespace std;

Stack::Stack(int size)

{

stackArray = new int[size];

stackSize = size;

top = -1;

}

Stack::Stack(const Stack &obj)

{

stackArray = new int[obj.stackSize];

stackSize = obj.stackSize;

top = obj.top;

for (int count = 0; count < stackSize; count++)

stackArray[count] = obj.stackArray[count];

}

Stack& Stack::operator=(const Stack &obj)

{

if (this != &obj)

{

delete [] stackArray;

stackArray = new int[obj.stackSize];

stackSize = obj.stackSize;

top = obj.top;

for (int count = 0; count < stackSize; count++)

stackArray[count] = obj.stackArray[count];

}

return *this;

}

Stack::~Stack()

{

delete [] stackArray;

}

bool Stack::push(int num)

{

if (top == stackSize - 1)

resize();

top++;

stackArray[top] = num;

return true;

}

bool Stack::pop(int &num)

{

if (!isEmpty())

{

num = stackArray[top];

top--;

return true;

}

else

return false;

}

bool Stack::peek(int &num)

{

if (!isEmpty())

{

num = stackArray[top];

return true;

}

else

return false;

}

bool Stack::isEmpty() const

{

return top == -1;

}

void Stack::resize()

{

stackSize *= 2;

int * tempStack = new int[stackSize];

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

tempStack[i] = stackArray[i];

delete [] stackArray;

stackArray = tempStack;

}

Explanation / Answer

Here is the completed code for adding 4 random numbers between 1-13 into the stack and displaying them. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks

//Code

#include<iostream>

#include<stdlib.h>

#include<time.h>

#include "Stack.h"

using namespace std;

//method to generate a random number between 1 and 13

int generateRandom(){

                int num= (rand()%13) +1;

                return num;

}

int main(){

                //seeding random number generator

                srand(time(NULL));

                //creating a stack with maximum capacity 4

                Stack intStack(4);

                int num;

                //pushing 4 random numbers between 1 and 13 into the stack

                for(int i=0;i<4;i++){

                                num=generateRandom();//generating number

                                intStack.push(num);//pushing

                }

                //displaying the numbers in the stack, by popping them

                //one by one.

                while(!intStack.isEmpty()){

                                intStack.pop(num);

                                cout<<num<<endl;

                }

}

//OUTPUT

9

10

8

5