An algorithm to show Stack in C program.

###An algorithm to show Stack in C program.
Flowchart given below:







Now we will implement this algorithm in a program:

Source Code in C++:
#include <iostream>
#include <stdlib.h>
using namespace std;
void push();
void pop();
void display();
#define max 10
int i,stack[max],top=-1;
int main(int argc, char const *argv[]) {
  int choice;
  do {
    std::cout << "*****Stack*****" << '\n';
    std::cout << "1.Push" << '\n';
    std::cout << "2.Pop" << '\n';
    std::cout << "3.Display" << '\n';
    std::cout << "4.Exit" << '\n';
    std::cout << "Enter your choice(1-4): " ;
    std::cin >> choice;
    switch (choice) {
      case 1:
      push();
      break;
      case 2:
      pop();
      break;
      case 3:
      display();
      break;
      case 4:
      exit(0);

    }

  } while(choice!=4);

  }
  void push(){
    int x;
    std::cout << "Which number you wanna push: ";
    std::cin >> x;
    if (top==max-1) {
      std::cout << "Stack is full." << '\n';
    }else{
      top=top+1;
      stack[top]=x;
    }
  }
  void pop(){
    if(top==-1){
      std::cout << "Stack is empty." << '\n';
    }else{
      std::cout << "Deleted element is " <<stack[top]<< '\n';
      top=top-1;
    }
  }
  void display(){
  if(top==-1){
    std::cout << "Stack is empty." << '\n';
  }else{
    std::cout << "Elements of the stack: " << '\n';
    for(i=0;i<=top;i++){
      std::cout << stack[i] << '\n';
    }
  }
  }


Output:
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 1
Which number you wanna push: 11
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 1
Which number you wanna push: 22
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 1
Which number you wanna push: 33
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 1
Which number you wanna push: 44
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 2
Deleted element is 44
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 3
Elements of the stack:
11
22
33
*****Stack*****
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4): 4

Press any key to continue . . .

Explanation:
Here we were asked for performing stack.You can see the algorithm above.Just follow them all.Here,I have provided the process to push and pop.When you need to push,you need to check whether the stack is full or not.If the top is in the (max-1) position then the stack is full.Else we can push element until the stack get full. Then we can pop element from the stack.The element we pushed last,it will be popped first.Befor pop operation,we have to check whether the stack is emty or not.If the stack is empty,then there is no element to pop out.


                                                           ***Happy Coding😊😊😊***

















No comments

Powered by Blogger.