0% found this document useful (0 votes)
6 views4 pages

Array-Based Stack Implementation in C

Uploaded by

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

Array-Based Stack Implementation in C

Uploaded by

p42477758
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Stack implementation using Array:

#include <stdio.h>

#include <stdlib.h>

#define MAX 5 // maximum size of stack

// Stack structure

struct Stack {

int arr[MAX];

int top;

};

// Function to initialize stack

void initStack(struct Stack *s) {

s->top = -1;

// Check if stack is full

int isFull(struct Stack *s) {

return s->top == MAX - 1;

// Check if stack is empty

int isEmpty(struct Stack *s) {

return s->top == -1;

// Push element onto stack

void push(struct Stack *s, int value) {

if (isFull(s)) {

printf("Stack Overflow! Cannot push %d\n", value);


} else {

s->arr[++s->top] = value;

printf("%d pushed to stack\n", value);

// Pop element from stack

int pop(struct Stack *s) {

if (isEmpty(s)) {

printf("Stack Underflow! Nothing to pop\n");

return -1;

} else {

return s->arr[s->top--];

// Peek top element

int peek(struct Stack *s) {

if (isEmpty(s)) {

printf("Stack is Empty!\n");

return -1;

} else {

return s->arr[s->top];

// Display stack elements

void display(struct Stack *s) {

if (isEmpty(s)) {

printf("Stack is Empty!\n");

} else {
printf("Stack elements (top to bottom):\n");

for (int i = s->top; i >= 0; i--) {

printf("%d\n", s->arr[i]);

// Main function

int main() {

struct Stack s;

initStack(&s);

int choice, value;

while (1) {

printf("\n=== Stack Menu ===\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Display\n");

printf("5. Exit\n");

printf("Enter choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to push: ");

scanf("%d", &value);

push(&s, value);

break;

case 2:
value = pop(&s);

if (value != -1)

printf("Popped: %d\n", value);

break;

case 3:

value = peek(&s);

if (value != -1)

printf("Top element: %d\n", value);

break;

case 4:

display(&s);

break;

case 5:

printf("Exiting...\n");

exit(0);

default:

printf("Invalid choice! Try again.\n");

return 0;

You might also like