Implement Stack using array in C



/*
www.troubleshootyourself.com
C Program to demonstrate stack implementation using array
*/


#include 
#include 
 
#define MAX 10
 
int STACK[MAX],TOP;
/* display stack element*/
void display(int []);
 
/* push (insert) item into stack*/
void Push(int [],int);
 
/* pop (remove) item from stack*/
void Pop(int []);
 
void main()
{
    int ITEM=0;
    int choice=0;
    TOP=-1;
 
    while(1)
    {
        
        printf("Enter Choice (1: display, 2: insert (PUSH), 3: remove(POP)), 4: Exit..:");
        scanf("%d",&choice);
 
        switch(choice)
        {
            case 1:
                display(STACK);
            break;
            case 2:
                printf("Enter Item to be insert :");
                scanf("%d",&ITEM);
                Push(STACK,ITEM);
            break;
            case 3:
                Pop(STACK);
            break;
            case 4:
                exit(0);
            default:
            printf("\nInvalid choice.");
            break;
        }
        
    }// end of while(1)
 
}
 
/*  function    : display(),
    to display stack elements.
*/
void display(int stack[])
{
    int i=0;
    if(TOP==-1)
    {
        printf("Stack is Empty .\n");
        return;
    }
 
    printf("%d <-- TOP ",stack[TOP]);
    for(i=TOP-1;i >=0;i--)
    {
        printf("\n%d",stack[i]);
    }
    printf("\n\n");
}
 
/*  
    Function to push the elements into stack.
*/
void Push(int stack[],int item)
{
    if(TOP==MAX-1)
    {
        printf("\nStack is full.\n");
        return;
    }
    TOP++;
    stack[TOP]=item;
}
 
/*  
    Function to pop an item from stack.
*/
void Pop(int stack[])
{
    int deletedItem;
    if(TOP==-1)
    {
        printf("Stack is empty..\n");
        return;
    }
 
    deletedItem=stack[TOP];
    TOP--;
    printf("%d deleted successfully\n",deletedItem);
    return;
}

Check and run the program here:

You can run the above program on codeboard editor and see the results. You are allowed to modify code and run. In the editor there is a menu at the top-right corner. Here you can see two buttons such as ‘Compile’ and ‘Run’.

Share this:
1 Comment
  1. This article presents clear idea for the new people of
    blogging, that truly how to do blogging and site-building.

Leave a reply

Troubleshootyourself
Logo