Saturday, April 15, 2017

Stack a Simple Implementation

/*Note:: Compile this code in *CodeBlocks* */

#include<stdio.h>

#define max 5 //defines the limit of our stack

 typedef struct stack{

    int arr[max]; //stack array
    int top; //top of the stack

 }stack;
 stack s1;

int full();
int empty();
int push();
int pop();
int display();



int main(){
    int choice;
    s1.top=0; //initiating top to start with operations on array
    while (1)
    {
        printf("\n\n\n\n");

        printf ("      1    ::    PUSH              \n");
        printf ("      2    ::    POP               \n");
        printf ("      3    ::    DISPLAY           \n");
        printf ("      4    ::    EXIT              \n");

        printf("\n\n\n\n");

        printf ("Enter your choice\n");
        scanf    ("%d", &choice);
        switch (choice)
        {
        case 1:
            push();
            break;
        case 2:
            pop();
            break;
        case 3:
            display();
            break;
        case 4:
            return;
        }


}

}
/*********************************************************************************************************/

int full(){ //To check if the stack is full
    if(s1.top==max){
        return 1;
    } else {
        return 0;}
}

int empty(){ //To check if the stack is empty
    if(s1.top==0){
        return 1;
    }else{
        return 0;}
}

int push(){ //To push integer element into the stack

    if(full()==1){printf("Stack Full");return;}
    int x;
    scanf("%d",&x);

    s1.arr[s1.top]=x;
    s1.top++;

}

int pop(){ //To pop integer element out of the stack

    if(empty()==1){printf("Stack is empty");return;}
    s1.top--;


}

int display(){ //To display currently available elements in the stack
    int i;
    printf("Stack Elements:: ");
    for(i=0;i<s1.top ;i++){
        printf("%d",s1.arr[i]);

    }
}