5,170 views
37 votes
37 votes
Write a C program to insert and delete values from a stack(to perform pop and push operations) using an array data structure

User Paradoja
by
2.6k points

1 Answer

16 votes
16 votes

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. \\");

}

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. \\");

}

else{

printf("Value removed: %c \\", 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\\", 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\\", 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\\", 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\\", 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\\", 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

Step-by-step 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.

User Ivan Kochurkin
by
2.9k points