Stack in C Program Example

How to write a c program to implement stack in C Programming ?


Stack is a specialized data storage structure (Abstract data type). Unlike, arrays access of elements in a stack is restricted.

Solution:
#include <stdio.h>
#include <stdlib.h>

#define SIZE 100

int stack[SIZE];
int top = 0;

void push(int value);
int pop();

int main()
{
push(10);
push(18);
printf("%d\n", pop());
push(12);
push(4);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());

return 0;
}

void push(int value)
{
if(top == SIZE)
{
printf("Stack Full\n");
exit(1);
}
stack[top++] = value;
}

int pop()
{
if(top == 0)
{
printf("Stack Empty\n");
exit(2);
}
return stack[--top];
}


Learn More :