Saturday, January 25, 2014

C++ Program to Stack ADT implementation Using Array

with 0 Comment
Stack ADT- Array Implementation
AIM:

  • To Write a C++ Program to Stack ADT implementation using array
Algorithm:
Step 1: Define a stack size.
Step 2: Read the stack operation.
Step 3: Read the stack element.
Step 4: Check the stack operation is Push or Pop.
Step 5: If operation is push then check the stack status.
i. If stack status is over flow we can’t push the element in to stack.
ii. Otherwise we can add the data into stack .
iii. Move top to next position.

Program:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
//using namespace std;
class stack
{
int stk[5];
int top;
public:
stack()
{
top=-1;
}
void push(int x)
{
if(top > 4)
{
cout <<"stack over flow";
return;
}
stk[++top]=x;
cout <<"inserted" <<x;
}
void pop()
{
if(top <0)
{
cout <<"stack under flow";
return;
}
cout <<"deleted" <<stk[top--];
}
void display()
{
if(top<0)
{
cout <<" stack empty";
return;
}
for(int i=top;i>=0;i--)
cout <<stk[i] <<" ";
}
};
main()
{
Clrscr();
int ch;
stack st;
while(1)
{
cout <<"\n1.push 2.pop 3.display 4.exit\nEnter ur choice";
cin >> ch;
switch(ch)
{
case 1: cout <<"enter the element";
cin >> ch;
st.push(ch);
break;
case 2: st.pop(); break;
case 3: st.display();break;
case 4: exit(0);
}
}
return (0);
}

OUTPUT:
1.push 2.pop 3.display 4.exit
Enter ur choice2
stack under flow
1.push 2.pop 3.display 4.exit
Enter ur choice1
enter the element2
inserted2
1.push 2.pop 3.display 4.exit
Enter ur choice1
enter the element3
inserted3
1.push 2.pop 3.display 4.exit
Enter ur choice2
deleted3
1.push 2.pop 3.display 4.exit
Enter ur choice1
enter the element5
inserted5
1.push 2.pop 3.display 4.exit
Enter ur choice3
5 2
1.push 2.pop 3.display 4.exit
Enter ur choice4

Result:

  • Thus, the stack ADT- array implementation program has been written and executed successfully.

0 comments:

Post a Comment

Powered by Blogger.

Blog Archive