"Write the code for a stack machine. Assume all operations occur on top of the stack. Push and pop are the only instructions that access memory" code example

Example 1: write a program to implement stack using array

#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<<"1) Push in stack"<<endl;
   cout<<"2) Pop from stack"<<endl;
   cout<<"3) Display stack"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter 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;
}

Example 2: program to implement stack for book details(book no, book name). implement push and display operation

def push(Books):
	Stack.append(Books)
	print 'Element:', Book, 'inserted successfully'
def pop():
	if Stack == []:
		print('Stack is empty!')
	else:
		print('Deleted element is',Stack.pop())

Example 3: stack operations, if executed on an initially empty stack? push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop().

5
5 3
5
5 2
5 2 8
5 2
5
5 9
5 9 1
5 9
5 9 7
5 9 7 6
5 9 7
5 9
5 9 4
5 9
5

Tags:

C Example