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; }
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.
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.