Solved programming problem

POP and PUSH in Stack in C.

Source code

#include <stdio.h>

int max=10;

typedef struct

{

   int top;

   int data[10];

}stack;

void push(stack *s, int item) ///save data at last

{

    if(s->top<max)

    {

        s->data[s->top] = item;

        s->top= s->top +1; ///increase the top value

    }

    else

    {

        printf("
Stack is Full
");

    }

}

int pop(stack *s) ///find the last element of the stack

{

    int item;

    if(s->top==0)

    {

       printf("
Stack is empty
 ");

       return -1;

    }

    else

    {

        s->top = s->top-1;

        item = s ->data[s->top];

    }

    return item;

}

int main()

{

    stack my_stack;

    int item;

    my_stack.top=0; ///save the 1st top value as 0

    push(&my_stack,1);///pass data for add

    push(&my_stack,2);

    push(&my_stack,3);

    ///print 3 stack data

    item = pop(&my_stack);

    printf("
Data: %d",item);

    item = pop(&my_stack);

    printf("
Data: %d",item);

    item = pop(&my_stack);

    printf("
Data: %d
",item);

    return 0;

}

Output


Data: 3
Data: 2
Data: 1

 

Join the discussion

Add your comment