Can you find bug??

Discussion in 'C' started by debleena_doll2002, Sep 8, 2008.

  1. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    This program is goin infinite loop....
    Code:
    #include<stdio.h>
    #define SIZE 5 
    int main()
    {
      int InpArray[SIZE]={1,2,2,3,4};
      int nSum=0,loop,missingNum;
      for(loop=0;loop<SIZE;loop++)
      {
       nSum += InpArray[loop];
       printf("hello");
      }
    
    //// Bug is in this loop, this loop is goin infinite...
      for(loop=0;loop<SIZE;loop++)
      {
        if(InpArray[(InpArray[loop])] > 0)
          InpArray[(InpArray[loop])] = -InpArray[(InpArray[loop])];
        else
          missingNum =  SIZE*(SIZE + 1)/2 - nSum + InpArray[(InpArray[loop])]; 
      }
    
      printf("Missing Number is = %d",missingNum);
    return 0;
    }
    
     
    Last edited: Sep 8, 2008
  2. nottoobad

    nottoobad New Member

    Joined:
    Sep 8, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    your loop is goin infinite because of your array index overflowed.
    when the loop = 0, InpArray[loop] = InpArray[0] = 1,then the if-clause returned true so 1 changed to -1,that's the problem,the c language never check the array index.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
    try defining this above your array and you will some other error.

    int nSum=0,loop,missingNum;
     
  4. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    You're problem is that you are accessing an array with a negative subscript. This
    accidentally modifies your loop variable, unless as shabbir noted, you move the
    array declaration to after the other variables. But of course this still leaves the
    problem of negative array indicies. If you "play computer" for just 2 iterations of
    the loop, you will see how you get the negative index.

    If you're just trying to find the missing number (presumably 5 in this case) then
    try this instead:
    * Set up another array of SIZE elements called Seen, initialized to 0.
    * Loop through InpArray and set the corresponding Seen element to 1.
    * Then loop through Seen and print out the element number of any
    zeroes you find.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice