Monday, June 8, 2015

C++ program to implement STACK using array and structure

/*-------------------------------------------------------------------------------------------------------------------------------
Author: Sujith
Program: Write a C++ program to implement STACK using array and structure
Prog name: stack.cpp
Date: 21-04-2015
---------------------------------------------------------------------------------------------------------------------------------*/
#include<iostream>
#define maxno 30
using namespace std;
class stack
{
int s[maxno];
int N;
public:
void initstack(int Size);
void push(int num);
int pop();
void displaystack();
};
main()
{
stack x;
system("clear");
int sum=0,b,i;
cout<<"\n Program to stack";
x.initstack(0);
cout<<"\n Enter 5 numbers into stack:\n";
for(i=0;i<5;i++){
cin>>b;
x.push(b);
}
sum=x.pop();
cout<<"value popped from stack="<<sum<<"\n";
x.displaystack();
return 0;
}
void stack::initstack(int Size)
{
N=Size;
}
void stack::push(int num)
{
if(N==maxno){
cout<<"stack is full";
}else{
N++;
s[N]=num;
}
}
int stack::pop()
{
int num;
if(N==0){
cout<<"stack is empty";
return 0;
}else{
num=s[N];
N--;
return num;
}
}
void stack::displaystack()
{
int i;
cout<<"values of stack:\n";
for(i=N;i>=1;i--){
cout<<s[i]<<"\n";
}
}
Output:
Program to stack
Enter 5 numbers into stack:
8
8
4
0
7
value popped from stack=7
values of stack:
0
4
8
8
[141740@localhost]

No comments:

Post a Comment