Forem

Cover image for Stack Implementation in C
Yash Desai
Yash Desai

Posted on • Edited on

1 2

Stack Implementation in C

We need these header files...

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
Enter fullscreen mode Exit fullscreen mode

Let's define some constants...

// constants
#define MAX 5              // Max capacity of a stack
#define ERR "\x1B[31m"     // Error Color
#define SUCCESS "\x1B[32m" // Success Color
#define RESET "\033[0m"    // Reset Color
Enter fullscreen mode Exit fullscreen mode

Constants defined in above lines of code such as ERR,SUCCESS and RESET will be used to color the text of printf(). MAX defines the maximum capacity of the stack

Now we'll declare a stack...

//declaration of stack
typedef struct stack
{
    int entry[MAX];
    int top;
} stack;
Enter fullscreen mode Exit fullscreen mode

Initialization of stack

//stack initialization
void init(stack *sptr)
{
    sptr->top = 0;
}
Enter fullscreen mode Exit fullscreen mode

A function to check if Stack is empty...

//checking stack is empty or not.
int isEmpty(stack *sptr)
{
    if (sptr->top == 0)
        return (1);
    else
        return (0);
}
Enter fullscreen mode Exit fullscreen mode

A function to check if stack is overflowed...

//checking stack is full or not.
int isFull(stack *sptr)
{
    if (sptr->top == MAX)
        return (1);
    else
        return (0);
}
Enter fullscreen mode Exit fullscreen mode

A function to push/insert a new element into the stack...

//Inserting element into stack
void push(stack *sptr)
{
    int item;
    if (isFull(sptr))
        printf(ERR "\tSTACK IS FULL" RESET);
    else
    {
        printf("\n\tEnter the element: ");
        scanf("%d", &item);
        sptr->entry[sptr->top] = item;
        sptr->top++;
    }
}
Enter fullscreen mode Exit fullscreen mode

A function to pop/remove elements from the stack...

//Deleting element from the stack
void pop(stack *sptr)
{
    int item;

    if (isEmpty(sptr))
        printf(ERR "\tSTACK IS EMPTY" RESET);
    else
    {
        sptr->top--;
        item = (sptr->entry[sptr->top]);
        printf(SUCCESS "\t%d HAS BEEN REMOVED" RESET, item);
    }
}
Enter fullscreen mode Exit fullscreen mode

A function to traverse though the stack or print all the elements of the stack

//Traversing the elements of stack
void traverse(stack *sptr)
{
    if (isEmpty(sptr))
        printf(ERR "\tSTACK IS EMPTY" RESET);
    else
    {
        int i;

        for (i = sptr->top - 1; i >= 0; i--)
            printf("\t-> %d\n", sptr->entry[i]);
    }
}
Enter fullscreen mode Exit fullscreen mode

And finally the main() function...

int main()
{
    stack s;
    int choice;

    init(&s);

    do
    {
        printf("\n 1. PUSH");
        printf("\n 2. POP");
        printf("\n 3. TRAVERSE");
        printf("\n 4. EXIT");
        printf("\n\nEnter the choice: ");
        scanf(" %d", &choice);
        switch (choice)
        {
        case 1:
            push(&s);
            break;
        case 2:
            pop(&s);
            break;
        case 3:
            traverse(&s);
            break;
        case 4:
            exit(0);
            break;
        default:
            printf(ERR "\tWRONG CHOICE" RESET);
        }
    } while (1);

    return 0;
    getch();
}
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Alt Text

Pushed 5 elements to the stack. (max capacity=5)

Alt Text

Alt Text

Removed two elements from the stack

Alt Text

Removed all elements until the stack is empty

Alt Text

Enjoy :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (2)

Collapse
 
clavinjune profile image
Clavin June

You can do this btw

//checking stack is empty or not.
int isEmpty(stack *sptr)
{
    return !sptr->top;
}
Enter fullscreen mode Exit fullscreen mode

I think you shouldn't do traverse in stack.

Collapse
 
yashdesai profile image
Yash Desai

Yes, I do agree with you. Thanks for correction!

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay