I dont get the right output. Please help me to fix it.

Whats wrong in the code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
using namespace std;
class stack{
private:
	int *st;
	int s;
	int top;
public:
	stack(int);
	//void set_values();
	//void get_values();
	void push(int);
	void pop(int &);
};

stack::stack(int x)
{
	s=x;
	top=0;
	st=new int[s];
}
/*
void stack::set_values()
{
	for(int i=0; i<s; ++i)
		st[i]=rand()%10;
}
void stack::get_values()
{
	for(int i=0; i<s; ++i)
		//cout<<st[i]<<endl
			;
}
*/
void stack::push(int x)
{
	if(top==s)
             cout<<"Stack full.\n";
	else{
		st[++top]=x;
		cout<<st[top]<<endl;
	}
}

void stack::pop(int &x)
{
	if(top==0)
        cout<"Stack empty.\n";

	else
		cout<<st[--top]<<endl;
}

int main()
{
	stack sc(10);
	
	//sc.set_values();
	//sc.get_values();
	
	for(int i=0; i<10; ++i){
		sc.push(rand()%10);
	}
	
	cout<<endl;
	for(int j=0; j<10; ++j){
		sc.pop(j);
	}
	
	system ("Pause");
	return 0;
}
Last edited on
Question is vague.

What's the wrong output. What are you getting/expecting?
Whats wrong in the code?
Quit asking this. Describe the problem: What should happen and what happens that makes you think that is wrong

On line 41 you cout the value after top is increased:
cout<<st[top - 1]<<endl;

something else?
Ok coder. Plz run the code and see the output.
ihutch, i'm expecting the poped values in order to pushed values.
Ok coder. Plz run the code and see the output.

We're not going to jump through hoops for you. If you want people to give their time and effort freely to help you, then the onus is on you to do everything you can to make this as easy as possible. That means clearly explaining what the problematic behaviour is, and what your expected behaviour is.

line 40 and 41 are wrong. Write it like so:
1
2
3
		st[top]=x;
		cout<<st[top]<<endl;
		++top;
I understood what you said, coder. Anyway, thanks again for support.
Topic archived. No new replies allowed.