Eragon
Eragon

Reputation: 53

wrong output from stack

The output is: 100 100
It should be: 9 100
I have called the push twice.When I call print, the output is wrong.

int main(){
    int i=9;
    Stackc s;
    s.push(i);
    i=100;
    s.push(i);
    s.print();
    return 0;
}

this is the .h file

class Stackc{
    int arr[100];
    int iTop;
public:
    int top();
    void push(int i);
    void pop();
    void print();
    Stackc();
};

this is the constructor

Stackc::Stackc(){
    iTop=-1;
    for(int i=0;i<100;i++)
        arr[i]=0;
}

this function pushes an element into the stack

void Stackc::push(int i){
    iTop++;
    arr[iTop]=i;
}

this is for printing the stack

void Stackc::print(){
    for(int i=0;i<=iTop;i++)
        cout<<arr[iTop]<<" ";
    cout<<endl;

}

Upvotes: 0

Views: 56

Answers (1)

Blaze
Blaze

Reputation: 16876

This line:

cout << arr[iTop] << " ";

Should be

cout << arr[i] << " ";

For the future I would recommend having a look at How to create a Minimal, Reproducible Example. For instance, a minimal example doesn't need to be across multiple files (unless the question is about how to handle multiple files). Ideally, the code can be run just copy/pasting one piece of code, like this:

class Stackc {
    int arr[100];
    int iTop;
public:
    Stackc() {
        iTop = -1;
        for (int i = 0; i < 100; i++)
            arr[i] = 0;
    }

    void push(int i) {
        iTop++;
        arr[iTop] = i;
    }

    void print() {
        for (int i = 0; i <= iTop; i++)
            std::cout << arr[i] << " ";
        std::cout << std::endl;

    }

};

int main() {
    int i = 9;
    Stackc s;
    s.push(i);
    i = 100;
    s.push(i);
    s.print();
    return 0;
}

I would also recommend the following Q&A:

Why is "using namespace std;" considered bad practice?

Upvotes: 3

Related Questions