0% found this document useful (0 votes)
2 views

StackOperations

The document contains a C program that implements a stack data structure using an array. It includes functions for initializing the stack, checking if it is empty or full, pushing and popping elements, and peeking at the top element. The main function demonstrates the usage of these stack operations.

Uploaded by

Deepak Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

StackOperations

The document contains a C program that implements a stack data structure using an array. It includes functions for initializing the stack, checking if it is empty or full, pushing and popping elements, and peeking at the top element. The main function demonstrates the usage of these stack operations.

Uploaded by

Deepak Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct
{
int arr[MAX_SIZE];
int top;
} Stack;

void initialize(Stack *stack)


{
stack->top = -1;
}

bool isEmpty(Stack *stack)


{
return stack->top == -1;
}

bool isFull(Stack *stack)


{
return stack->top == MAX_SIZE - 1;
}
void push(Stack *stack, int value)
{
if (isFull(stack))
{
printf("Stack Overflow\n");
return;
}
stack->arr[++stack->top] = value;
printf("Pushed %d onto the stack\n", value);
}

int pop(Stack *stack)


{
if (isEmpty(stack))
{
printf("Stack Underflow\n");
return -1;
}
int popped = stack->arr[stack->top];
stack->top--;
printf("Popped %d from the stack\n", popped);
return popped;
}

int peek(Stack *stack)


{
if (isEmpty(stack))
{
printf("Stack is empty\n");
return -1;
}
return stack->arr[stack->top];
}

int main()
{
Stack stack;
initialize(&stack);

push(&stack, 3);
printf("Top element: %d\n", peek(&stack));

push(&stack, 5);
printf("Top element: %d\n", peek(&stack));

push(&stack, 2);
printf("Top element: %d\n", peek(&stack));

push(&stack, 8);
printf("Top element: %d\n", peek(&stack));

while (!isEmpty(&stack))
{
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
}
return 0;
}

You might also like