keystrokker keystrokker - 1 month ago 6
C Question

Static stack operations in C

i'm trying to perform all operations(push, pop, peep, update, show) on stack using array in C.It's working fine when i am calling the

show()
at last after calling all of the functions that i need. But whenever i call
show()
before any of the operations than it is not giving me the appropiate result.
I'm using following code:

int main()
{
push(1);
push(2);
push(3);
push(4);
push(6);
pop();
push(5);
show();//line 8
//push(7);//line 9
//pop();
//peep();
//update();
//show();//line 13
return;
}

void push(int num){//insert an item

if(top==MAXSIZE-1)
{
printf("Overflow condition");
return;
}
top++;
stack[top]=num;
//return;
}

void pop()//delete a item from top
{

int num;
if(top==-1)
{
printf("Underflow condition");
return;
}
num=stack[top];
top--;
//return;
}

void show()//display elements
{

if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]);
}
//return;
}

void peep()//extract information
{

int loc,num;
printf("enter location:\n");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
num=stack[top-loc+1];
printf("\nItem at location %d is %d",loc,num);
}
}

void update(){//update information

int loc,item;
printf("enter new item:");
scanf("%d",&item);
printf("enter location:");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
stack[top-loc+1]=item;
printf("\nItem inserted");
}
}


Here after calling
show()
,top will point to -1(empty) at line 8,so after that following consequences will be:


  • push()
    will insert at position 1 instead of at top.

  • pop()
    will show underflow condition.

  • peep()
    and update will go in if condition.



So how can i set top to the top element in the stack after once calling the
show()
?
Thanks.

Answer

Your show() method modifies the top pointer and this is wrong:

void show()//display elements
{

    if(top==-1){
        printf("Underflow");
        return;
    }
    while(top!=-1){
        printf("%d\n",stack[top--]); // <--- here 'top--' will modify the top pointer
    }
    //return;
}

You can change the show() method like this:

void show()//display elements
{

    if(top==-1){
        printf("Underflow");
        return;
    }
    int i = top; // introducing a new variable to iterate through the stack
    while(i!=-1){
        printf("%d\n",stack[i--]); // now 'i' is modified
    }
    //return;
}
Comments