Here we see how to implement the stack using C array data type:
#include <stdio.h>
#define MAX 5 //maximum size of stack
int top = -1; //top of stack
int stack[MAX]; // stack
int pop();
void push(int);
void display(); // for displaying stack elements
int main(){
push(1);
push(3);
push(5); display();
pop();
pop(); display();
pop();
pop();
return 0;
}
void push(int item){
if(top == MAX-1){ //check for overflow
printf("Stack overflow\n");
}
else{
stack[++top] = item;
printf("Pushed item = %d\n", item);
}
}
int pop(){
if(top == -1){ // check for underflow
printf("Stack underflow\n");
}
else{
return stack[top--];
}
}
void display(){
printf("The stack elements are: ");
for( int i = 0; i <= top; i++){
printf("%d ", stack[i]);
}
printf("\n");
}
Output:
Pushed item = 1
Pushed item = 3
Pushed item = 5
The stack elements are: 1 3 5
The stack elements are: 1
Stack underflow
Comments
Post a Comment