Ayush Bhagoliwal
Ayush Bhagoliwal

Reputation: 35

error in stack Operation on an array in push operation

I was trying to implement stack operation and while doing push operation the value being entered is always 0. If I enter any number the result in the array loaded is always 0.

//Stack Operation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int stack[10];
int top=0;
void push()
{
    int i;
    printf("Enter the element you want to add");
    scanf("%d",& stack[top]);
    top++;
    printf("%d",stack[top]);
    printf("The element is added\n");
    for(i=0;i<top;i++) {
        printf("%d",stack[top]);
    }
}
int pop()
{
    top--;
    return(stack[top]);
}
void display()
{
    int i;
    for(i=0;i<=top;i++);
    {
        printf("%d \t",stack[i]);
    }
}
void main()
{
    int ch;
    clrscr();
    label:
    printf("1---->Push\n");
    printf("2---->Pop\n");
    printf("3----->Display\n");
    printf("4-----> Exit\n");
    printf("Enter your choice");
    scanf("%d",&ch);
    if(ch==1) {
        clrscr();
        push();
        goto label;
    }
    if(ch==2) {

        int f;
        clrscr();
        f=pop();
        printf("Poped Element %d",f);
        goto label;
    }
    if(ch==3) {
        clrscr();
        display();
        goto label;
    }
    if(ch==4) { 
        exit(0);
    }
    getch();
}

Upvotes: 0

Views: 71

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

As I understand, your indexing is wrong. You may want to change

for(i=0;i<top;i++)
    {
    printf("%d",stack[i]);  // change top to i
    }

That said,

  • In push(), youre doing

    scanf("%d",& stack[top]);
    top++;
    printf("%d",stack[top]);
    

    which is incrementing top before printing the scanned value. You don't want to increment top before printing.

  • in your push function, the index top is unbound, wheras the actual array is bound (10 elements). You should at least put a check on top value (<10 or alike) to make sure the index is within bounds.

Upvotes: 3

dbush
dbush

Reputation: 224917

Several issues here:

  • When inserting, you increment top before printing the top value, so it always prints 1 element after the top.
  • When printing after inserting, you print stack[top] instead of stack[i].
  • In display, you have a stray semicolon right after the for, resulting in an empty loop body.

Upvotes: 0

Related Questions