Answer :

Answer:

#include<stdio.h>

// Method to insert a value into a stack

void push(char value, char myStack[], int *top, int sizeOfStack){

   if(*top == -1){

       myStack[sizeOfStack - 1] = value;

       *top = sizeOfStack - 1;

   }

   else if(*top == 0){

       printf("Stack is full. \n");

   }

   else{

       myStack[(*top) - 1] = value;

       (*top)--;

   }

}

//Method to remove a value from a stack

void pop(char myStack[], int *top, int sizeOfStack){

   if(*top == -1){

       printf("Stack is empty. \n");

   }

   else{

       printf("Value removed: %c \n", myStack[(*top)]);

       // Now if the value removed was the last value in the stack

       // you should set top to -1.  

       // This would show that the stack is now empty

       if((*top) == sizeOfStack - 1){

           (*top) = -1;

       }

       else{

           (*top)++;

       }

   }

}

//Method to test the pop and push methods

int main() {

 //variable to hold the size of stack

 int sizeOfStack = 6;

 //create the stack

 char myStack[sizeOfStack];

 

 //set the top to -1

 //this is to show that the stack is initially empty

 int top = -1;

 //insert a value tot the stack

 push('x', myStack, &top, sizeOfStack);

 //print the value on the top

 printf("Value on top of stack: %c\n", myStack[top]);

 //insert another value to the stack

 push('y',myStack, &top, sizeOfStack);

 //print the value on the top of the stack

 printf("Value on top of stack: %c\n", myStack[top]);

 //insert another value to the stack

 push('z',myStack, &top, sizeOfStack);

 //print the value on the top of the stack

 printf("Value on top of stack: %c\n", myStack[top]);

 //remove the last inserted value

 pop(myStack, &top, sizeOfStack);

 //print the value on the top of the stack

 printf("Value on top of stack: %c\n", myStack[top]);

 //remove another value

 pop(myStack, &top, sizeOfStack);

 //print the value on the top of the stack

 printf("Value on top of stack: %c\n", myStack[top]);

 return 0;

}

Sample Output:

Value on top of stack: x

Value on top of stack: y

Value on top of stack: z

Value removed: z  

Value on top of stack: y

Value removed: y  

Value on top of stack: x

Explanation:

The code above has been written in c and it contains comments explaining important parts of the code. Please go through the comments.

It also contains a sample output resulting from the run of the program.

Other Questions