Can someone explain the misbehaviour of this code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    Can someone explain the misbehaviour of this code

    I was trying to solve a problem then i observed a misbehaviour in my code,it is asking for input continuosly how much input i give and this is only happening for some particular inputs.
    Code:
    #include<stdio.h>
      void fun(int a[],int n,int k)
    	{
        	int i,j,t;
        	int b[1000];
         	for(i=0;i<n;i++)
    		{
    			b[i]=1;
    			while(a[i]!=1&&a[i]!=0)
    			{
    				if(a[i]%2==1)
    				b[i]++;
    				a[i]=a[i]/2;
    			}
                         if(a[i]==0)
                         b[i]=0;
    		}
    		for(i=0;i<k;i++)
    		{
    			int max=i;
    			for(j=i;j<n-1;j++)
    			{
    				if(b[j]>b[max])
    				{
    					max=j;
    				}
    			}
    			t=a[i];
    			a[i]=a[max];
    			a[max]=t;
    			t=b[i];
    			b[i]=b[max];
    			b[max]=t;
    		printf("%d",a[i]);
    		}
    	}
    	int main()
    	{ 
    		int t,n,k,i,j,a[1000];
            scanf("%d",&t);
            for(i=0;i<t;i++)
            {
                scanf("%d %d",&n,&k);
            	for(j=0;j<n;j++)
            	{
            	     scanf("%d",&a[j]);
            	}
            	fun(a,n,k);
            }
        }
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    I suggest you add code after lines 40 and 43 to test the entered values of t, n, and k to make sure they make sense.

    What should happen if a[i] is negative? Should the tests on lines 9 and 11 also check for -1?

    Comment

    Working...