Question

I am implementing a stack using arrays here is the programme i have written

#include<stdio.h>

int path[100];  //stores the path vertices
int tp=-1;      //tp is top pointer in stack
//int graph_matrix[100][100];   
//int child_matrix[100][100];

void push(int vi)
{
  int i=0;
  tp++;
  path[tp]=vi;
  printf("pushing %d in index %d value: %d \n",vi,tp,path[tp]);
  for(i=0;i<5;i++)
    printf("%d  ",path[i]);
}

void pop()
{
  printf("popping %d\n",path[tp]);
  if(tp==-1) {
    printf("stack empty\n");
    goto end2;
  }

  path[tp]=-1;
  tp--;

end2:
  printf("");
}


int eg()
{
  int i=0;
  for(i=0;i<100;i++) 
    path[i]=-1;     //initializing path array tp -1

  print_path();
  push(30);
  print_path();
  push(40);
  print_path();
  push(50);
  print_path();
  //pop();
  print_path();
  push(60);
  print_path();
}

void print_path()
{
  int j=0;

  for(j=0;j<10;j++)
  {
    printf("%d    ",path[j]);
    j++;
  }
  printf("\n");
}

int main()
{
  eg();
  return 0;
}

But THe output shows me something else:

Output:

-1 -1 -1 -1 -1

pushing 30 in index 0 value: 30

30 -1 -1 -1 -1 30 -1 -1 -1 -1

pushing 40 in index 1 value: 40

30 40 -1 -1 -1 30 -1 -1 -1 -1

pushing 50 in index 2 value: 50

30 40 50 -1 -1 30 50 -1 -1 -1

30 50 -1 -1 -1

pushing 60 in index 3 value: 60

30 40 50 60 -1 30 50 -1 -1 -1

Can anyone please explain the output?

Was it helpful?

Solution

As mentioned in the comments, you increment the loop variable twice.

Why not simply print the stack in its entirety instead of only 5 elements?

void print_path(void)
{
  int j;

  for(j = 0; j <= tp; j++)
  {
    printf("%d ", path[j]);
  }
  printf("\n");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top