Array Representation Using Stack

Array Representation Using Stack

Table of contents

No heading

No headings in the article.

ARRAY REPRESENTATION OF STACK:-

(LIFO- LAST IN FIRST OUT)

EXAMPLE:

Initially:

empty stack

top = -1

step 1: push 3

top ++

step 2: push 5

top++

step 3,4: push 7,9

top + +

step 5: push 2

stack overflow

step 6: pop

top--

step 7,8,9: pop

top--

step 10: pop

stack underflow

PUSH OPERATION:

step 1: start

step 2: if (top=length-1)

then

print("stack overflow")

return

endif

step 3: top=top+1

step 4: read n

step 5: arr[top]=n

step 6: stop

POP OPERATION:

step 1: start

step 2: if top =-1

then

print("stack underflow")

return

endif

step 3: n=arr[top]

step 4: print n

step 5: top=top-1

step 6: stop

PROGRAM:

#include <iostream>
using namespace std;

#define max 30
class stack
{
int a[max], top;

public:
stack()
{
top = -1;
}

void push(int n)
{
if(top == max-1)
{
cout<<"stack overflow"<<endl;
return;
}
top++;
a[top]=n;
}

void pop()
{
if(top==top-1)
{
cout<<"stack underflow"<<endl;
return;
}
int n=a[top];
cout<<"popped element"<<a[top]<<endl;
top--;
}
void display()
{
if(top == -1)
{
cout<<"empty stack"<<endl;
}
else
{
for(int i=top;i>=0;i--)
{
cout<<a[i]<<endl;
}
}
}

void peep()
{
if(top == -1)
{
cout<<"empty stack"<<endl;
}
else
{
cout<<a[top]<<endl;
}
}
};

int main()
{
stack ob;
while(1)
{
cout<<"enter 1 for push"<<endl;
cout<<"enter 2 for pop"<<endl;
cout<<"enter 3 for display"<<endl;
cout<<"enter 4 for peep"<<endl;
cout<<"enter 5 for exit"<<endl;

int choice;
cin>>choice;

switch (choice)
{
case 1:
cout<<"enter a value for push operation"<<endl;
break;
case 2:
ob.pop();
break;
case 3:
ob.display();
break;
case 4:
ob.peep();
break;
case 5:
cout<<"end of program"<<endl;
break;
default:
cout<<"invalid option"<<endl;
}
if(choice==5)
break;
}
}

Run The CODE:

https://onlinegdb.com/mgcqIqnYd