0% found this document useful (0 votes)
2 views3 pages

stack using array

c++ stack using array program

Uploaded by

saravanaoctaquad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

stack using array

c++ stack using array program

Uploaded by

saravanaoctaquad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

// IMPLEMENTATION OF STACK USING ARRAYS

#include <iostream.h>
#include <conio.h>
#include <ctype.h>

#define size 100

int top = -1;


int flag = 0;

class stacks {
public:
void push(int *, int);
int pop(int *);
void display(int *);
};

/*----------- PUSH -----------*/


void stacks::push(int s[], int d)
{
if (top == size - 1)
flag = 0; // overflow
else {
flag = 1;
++top;
s[top] = d;
}
}

/*----------- POP ------------*/


int stacks::pop(int s[])
{
int popped;
if (top == -1) { // underflow
popped = 0;
flag = 0;
} else {
flag = 1;
popped = s[top];
--top;
}
return popped;
}

/*---------- DISPLAY ---------*/


void stacks::display(int s[])
{
if (top == -1)
cout << "Stack is empty";
else
for (int i = top; i >= 0; --i)
cout << "\n\t" << s[i];
}

/*============= MAIN =========*/


void main()
{
clrscr();

stacks stk;
int stack[size];
int data;
char choice; // must be char to match 'i','p','q'
int quit = 0;

/*--- SINGLE do-while LOOP ---*/


do {
cout << "\nPush->i Pop->p Quit->q";
cout << "\nInput the choice: ";
cin >> choice;
choice = tolower(choice);

switch (choice)
{
case 'i': // PUSH
cout << "\nInput the element to be pushed: ";
cin >> data;
stk.push(stack, data);

if (flag) {
cout << "\nAfter inserting";
stk.display(stack);
if (top == size - 1)
cout << "\nStack is full";
} else
cout << "\nStack overflow after pushing";
break;

case 'p': // POP


data = stk.pop(stack);
if (flag) {
cout << "\nData is popped: " << data;
cout << "\nRest data in stack is as follows:";
stk.display(stack);
} else
cout << "\nStack underflow";
break;

case 'q': // QUIT


quit = 1;
break;

default:
cout << "\nInvalid choice";
}

} while (!quit); // <-- matching while

getch();
}

You might also like