Answer to Question #244780 in C++ for Myname

Question #244780
Write a program to implement the stack using an array.
Note: The code should have the modularity and should include following function (
1
Expert's answer
2021-10-01T01:30:48-0400
#include <iostream>
using namespace std;
int arr[100], x=100, top=-1;
void push(int item) {
   if(top>=x-1)
   cout<<"Stack Overflow"<<endl;
   else {
      top++;
      arr[top]=item;
   }
}
void pop() {
   if(top<=-1)
   cout<<"Empty stack"<<endl;
   else {
      cout<<"Removed element is "<< arr[top] <<endl;
      top--;
   }
}
void show() {
   if(top>=0) {
      cout<<"Stack Contents:";
      for(int i=top; i>=0; i--)
      cout<<arr[i]<<" ";
      cout<<endl;
   } else
   cout<<"No element in the stack";
}
int main() {
   int choice, item;
   cout<<"1) Insert into the stack"<<endl;
   cout<<"2) Remove item from the stack"<<endl;
   cout<<"3) Display contents of the stack stack"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter an option: "<<endl;
      cin>>choice;
      switch(choice) {
         case 1: {
            cout<<"Enter a number to insert"<<endl;
            cin>>item;
            push(item);
            break;
         }
         case 2: {
            pop();
            break;
         }
         case 3: {
            show();
            break;
         }
         case 4: {
            cout<<"Terminated"<<endl;
            break;
         }
         default: {
            cout<<"Wrong Option"<<endl;
         }
      }
   }while(choice!=4);
   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS