Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

LAB MANUAL-9

Object Oriented Programming


CS-124L

Submitted to:
Mr. Fahad Majeed
Submitted by:
Rashid Sharif 18-ENC-25

Department of Electronic Engineering


University of Engineering and Technology Taxila
Example:
Write a C++ program to implement a stack using array.
#include<iostream>
#include<conio.h>
using namespace std;
class stack
{
private:
int arr[5];
int top;
public: Stack ()
{
top = -1;
}
void push(int v)
{
if(top==4)
cout<<"Stack is full."<<endl; else
{
arr[++top] = v;
cout<<"Data pushed successfully."<<endl;
}}
int pop()
{
if(top==-1)
{
cout<<"Stack empty.";
return NULL;
}
else
return arr[top--];
}}
;
int main()
{
stack s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
s.push(60);
cout<<s.pop()<<endl; cout<<s.pop()<<endl; cout<<s.pop()<<endl;
cout<<s.pop()<<endl; cout<<s.pop()<<endl; cout<<s.pop()<<endl; cout<<s.pop()<<endl;
getch();
}
OUTPUT:
Write down the code to push and pop the values from the stack. Try to create
the menu as follows

CODE:
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<" Main Menu "<<endl;
cout<<" PRESS 1 FOR PUSHING ONTO THE STACK"<<endl;
cout<<" PRESS 2 FOR POPING FROM THE STACK"<<endl;
cout<<" PRESS 3 FOR DISPLAYING THE VALUES OF STACK"<<endl;
cout<<" PRESS 4 TO EXIT FROM THE PROGRAM"<<endl;
do {
cout<<"PLEASE ENTER YOUR CHOICE"<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
OUTPUT:

You might also like