#include <stdio.
h>
#include <stdlib.h>
#define MAX_SIZE 100 // Maximum size of the stack
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
// Function to create an empty stack
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
if (stack == NULL) {
printf("Memory allocation failed\n");
return NULL;
stack->top = -1; // Initialize top to -1 (empty stack)
return stack;
// Function to check if the stack is empty
int isEmpty(Stack* stack) {
return stack->top == -1;
// Function to check if the stack is full
int isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
// Function to add an element to the stack (push)
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack overflow\n");
return;
stack->data[++stack->top] = value; // Increment top and then add the element
// Function to remove and return the top element (pop)
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow\n");
return -1; // Or any appropriate error value
return stack->data[stack->top--]; // Return the top element and then decrement top
// Function to view the top element (peek)
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1; // Or any appropriate error value
}
return stack->data[stack->top];
// Function to get the size of the stack
int size(Stack* stack) {
return stack->top + 1;
int main() {
Stack* stack = createStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("Top element: %d\n", peek(stack)); // Output: 30
printf("Popped element: %d\n", pop(stack)); // Output: 30
printf("Popped element: %d\n", pop(stack)); // Output: 20
printf("Popped element: %d\n", pop(stack)); // Output: 10
printf("Size of stack: %d\n", size(stack)); // Output: 0
free(stack); // Free the allocated memory
return 0;