I am trying to figure out what is wrong with my C++ code. This code is implement
ID: 3751588 • Letter: I
Question
I am trying to figure out what is wrong with my C++ code. This code is implementing the stack structure within a class. The output should be: X = 3, Y = 9, 7, 13, 4, 7 in a stacked form. My code outputs x = 3 and y = 9 but does not output 7,13,4,7, and instead outputs random numbers and zeros.
My Output:
Header File:
#include <cassert>
class stackType {
private:
int arrayStack[];
int stackTop;
int stackSize;
public:
stackType();
bool isEmpty();
bool isFull();
void push(int newData);
void pop();
int top();
void intStack();
};
stackType::stackType(){
stackTop = 0;
stackSize = 100;
}
bool stackType::isEmpty(){
return (stackTop == 0);
}
bool stackType::isFull(){
return (stackTop == stackSize);
}
void stackType::push(int newData){
if (!isFull()){
arrayStack[stackTop] = newData;
stackTop++;
}
else{
cout << "Can't push when stack is full !" << endl;
}
}
void stackType::pop(){
if (!isEmpty()){
stackTop--;
}
else{
cout << "Can't pop from an empty list !" << endl;
}
}
int stackType::top(){
assert (stackTop != 0);
return arrayStack[stackTop-1];
}
CPP File:
#include <iostream>
using namespace std;
#include "arrayStack.h"
int main()
{
stackType stack;
int x;
int y;
// Show what is output by the following segment of code:
x = 4;
y = 0;
stack.push(7);
stack.push(x);
stack.push(x + 5);
y = stack.top();
stack.pop();
stack.push(x + y);
stack.push(y - 2);
stack.push(3);
x = stack.top();
stack.pop();
cout << "x = " << x << endl;
cout << "y = " << y << endl;
while (!stack.isEmpty())
{
cout << stack.top() << endl;
stack.pop();
}
system("PAUSE");
return 0;
}
Explanation / Answer
Hi There :)
Your entire code is fine except
int arrayStack[];
---> you cant declare the static array without size.
Correction : int arrayStack[100];
just change the above line and program is good to run.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.