Table of Contents
Introduction to arrays as class member data
How to implement stacks in c++? How arrays are used as data members of Class? So far it is seen only the variables and functions can be used as members of a class. But arrays can also be used as data members of a class. An application of this is the implementation of stacks. Before understanding how it is done lets have a brief introduction of stack.
How to implement stacks in c++?
stacks are special data structures that are used for storing and then removing data items from the memory. Stacks work on the LIFO (last in first out) principal. The simple example is piling up the plates and then removing the one from the top. It means the plate that was stored at last is removed at first. Generally speaking in computers engineering terms whenever the control of a program is transferred from one address to another, the address to be returned at is stored in stack. Similarly when a function is called, the control of program is transferred to the definition of the function. In order to maintain the sequence of the program the address of the next instruction from where the call was made is stored in stack. There are many examples that show the significance of stack in computer programming. Consider the following example which shows how arrays as class members implement stack.
Example
class stack
{
private:
enum {max=10};
int st[max];
int top;
public:
stack()
{
top=0;
}
void push(int var)
{
st[++top]=var;
}
int pop()
{
return st[pop–];
}
};
void main()
{
clrscr();
stack s1;
s1.push(11);
s1.push(22);
cout<<“1: “<<s1.pop()<<endl;
cout<<“2: “<<s2.pop()<<endl;
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout<<“3:”<<s1.pop()<<endl;
cout<<“4:”<<s1.pop()<<endl;
cout<<“5:”<<s1.pop()<<endl;
cout<<“6:”<<s1.pop()<<endl;
}
when a value is stored in a stack it is called pushing and when a data item is removed from the stack it is called popping. The above program uses an object s1 for pushing two values in the stack and then pops off them. Then four more data items are pushed and popped off from the stack. It is to remember that the items are always popped off in the reverse order: last pushed first popped.
Also read here
- what is the scope of a variable? How you define the lifetime of local and global variables in programming?
- How do you define classes and objects in C++?
- what is the switch Statement in C++?
- How many types of inheritance are here in C++?
- What are the decision making statements in C++?
- How to use rand() function in C++?
- What are the strings in C++?
- Design a matrix calculator in c++
- How to define structures in C++? What is meant by structures within structures?
- How to define and call functions in C++?
- What is the difference between if and if-else statement ?
- What is the inheritance in C++?
- How to implement recursion in C++? Explain with an example
2 thoughts on “How to implement stacks in c++?”