title: Why does this DP solution to the 0/1 Knapsack Problem not give the correct output with GCC?
body: <pre><code>#include&lt;stdio.h&gt;
  
  int max(int a,int b)
  {
      if(a&gt;b)
          return a;
      else
          return b;
  }
  
  void knapsack(int m,int n,int w[],int p[])
  {
      int v[10][10],x[10],i,j;
      for(i=0;i&lt;=n;i++)
      {
          for(j=0;j&lt;=m;j++)
          {
              if(j==0||i==0)
                  v[i][j]=0;
              if(j-w[i]&lt;0)
                  v[i][j]=v[i-1][j];
              else
                  v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
          }
      }
      for(i=0;i&lt;=n;i++)
      {
          for(j=0;j&lt;=m;j++)
              printf("%d\t",v[i][j]);
          printf("\n");
      }
      printf("THE OPTIMAL SOLUTION IS:%d",v[n][m]);
      for(i=1;i&lt;=n;i++)
          x[i]=0;
      i=n;
      j=m;
      while(i&gt;0 &amp;&amp; j&gt;0)
      {
          if(v[i][j]!=v[i-1][j])
          {
              x[i]=1;
              j=j-w[i];
          }
          i--;
      }
      printf("THE OPTIMAL SET OF WEIGHTS IS:");
      for(i=1;i&lt;=n;i++)
          if(x[i]==1)
              printf("%d\t",i);
      printf("\n");
  }
  
  int main()
  {
      int w[10],p[10],i,m,n;
      printf("ENTER THE NUMBER OF ITEMS:");
      scanf("%d",&amp;n);
      printf("ENTER THE WEIGHTS OF THE ITEMS:");
      for(i=1;i&lt;=n;i++)
          scanf("%d",&amp;w[i]);
      printf("ENTER THE PROFITS OF THE ITEMS:");
      for(i=1;i&lt;=n;i++)
          scanf("%d",&amp;p[i]);
      printf("ENTER THE CAPACITY OF KNAPSACK:");
      scanf("%d",&amp;m);
      knapsack(m,n,w,p);
      return 0;
  }
  </code></pre>
  
  <p>SAMPLE OUTPUT:</p>
  
  <pre><code>chaitanya@chaitanya-laptop:~/Desktop/My prog$ ./a.out
  
  ENTER THE NUMBER OF ITEMS:5
  
  ENTER THE WEIGHTS OF THE ITEMS:3
  2
  1
  2
  3
  
  ENTER THE PROFITS OF THE ITEMS:2
  3
  2
  3
  2
  
  ENTER THE CAPACITY OF KNAPSACK: 8
  
  0   -72 -1080992920 -72 0   1   -1080993280 0   13403040    
  0   -72 -1080992920 2   0   1   -70 2   13403040    
  0   -72 3   2   0   5   3   4   13403040    
  0   2   3   5   4   5   7   5   13403040    
  0   2   3   5   6   8   7   8   13403040    
  0   2   3   5   6   8   7   8   13403040    
  
  THE OPTIMAL SOLUTION IS:13403040
  
  THE OPTIMAL SET OF WEIGHTS IS:
  </code></pre>
  
  <p><strong>Note:</strong> The same program produces a legitimate output for the same input when compiled in the "Turbo C" compiler.</p>
  
  <p>So that leads me to believe that i am not adhering to C standards. Is that so?</p>