Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

I'm getting an infinite loop ? i don't know why ? ( c language )

hey guys can you check out this code i wrote , Its not working and i can't figure it out ?

include <unistd.h>

include <time.h>

include <stdio.h>

include <stdlib.h>

int main() { int arr[100]; int i = 0; int loop = 0; int tmp = -1;

while (i <= 99)
{
    arr[i] = -1;
    i++;
}
while (loop <= 1000)
{
    i = 0;
    while (i <= 99) // A
    {
        srandom(time(0)+i);
        if (arr[i] == -1)
        {
            arr[i] = random();
            i = 100;
        }
        i++;
    }
    i = 0;
    while (i <= 99)
    {// B
        if (arr[i] > 0)
        {
            if (tmp < arr[i])
            {
                tmp = arr[i];
                loop++;
                i = 100;
                printf("loop=%d -- tmp=%d  --  arr[%d]=%d\n",loop, tmp, i, arr[i]);
            }
        }
        i++;
    }
}

}

1 Answer

At some point in the B loop, tmp will get assigned the maximum value out of all the values in arr. Once that happens, the if (tmp < arr[i]) condition will never be true again, so you'll never increment your loop variable from that point forward. Therefore, you'll never exit your main loop.

What are you trying to accomplish? There's probably a simpler way of going about it.