DS - Lab 1.3
DS - Lab 1.3
2. Task to be done:
3. Algorithm:
PUSH –
o We initialized top as -1.
o If top>= maximum size of stack then overflow condition is applied.
o Else top is incremented by 1 and element is inserted at that top position using
stack[top]=element.
POP –
o If top<0 then underflow condition is applied.
o Else element present at topmost position is removed as stack follows LIFO rule
and we return stack[top--] to the main calling function.
4.Flowchart:
START
PUSH POP
Yes No Yes No
Top++
Top++ Cannot insert Return
Cannot insert
Stack[top]=element element stack[top--]
element
END
5. Code
#include <iostream>
#include<stdlib.h>
#define size 10
using namespace std;
int stack[size];
int top = -1;
void push(int element){
if(top>=size){
cout<<"Overflow condition,cannot insert element into the stack"<<endl;
return;
}
top++;
stack[top]=element;
cout<<element<<" pushed up successfully"<<endl;
int pop(){
if (top<0){
cout<<"Underflow condition,stack is empty"<<endl;
return INT_MIN;
}
return stack[top--];
}
int main(){
int choice,element;
cout<<"Stack Implementation program"<<endl;
cout<<"________________________________________________________________"<<endl
;
cout<<"PRESS "<<endl;
cout<<"1-Insert an element"<<endl;
cout<<"2-Remove an element"<<endl;
cout<<"3-To display stack size"<<endl;
cout<<"4-Exit the program"<<endl;
cout<<"________________________________________________________________"<<endl
;
while(1){
cout<<"--------------------------------------------------------------------\n"<<endl;
cout<<"Eenter your choice: ";
cin>>choice;
cout<<"--------------------------------------------------------------------\n"<<endl;
switch(choice) {
case 1:
cout<<"Enter the element to insert in the stack: ";
cin>>element;
push(element);
break;
case 2:
element=pop();
if(element!=INT_MIN){
cout<<"Removed element is: "<<element<<endl;
cout<<"Remaining elements in the stack are: ";
for(int i=0;i<=top;i++){
cout<<stack[i]<<"\t";
}
}
cout<<"\n";
break;
case 3:
cout<<"Stack size: "<<top+1<<endl;
break;
case 4:
cout<<"Exiting the program";
exit (0);
default:
cout<<"Incorrect choice,enter again\n\n";
break;
}
}
return 0;
}
3. Basics of stacks.
Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):