Thread: infinite loop

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    28
    Rep Power
    0

    infinite loop


    Hi,

    Im writing the following code to check for doubles in an array. It turns into an infinite loop after I set i = -1. I was wondering why this is happening and how can I get around this..

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    #define K 50

    void main(void)
    {

    int num,i,j,k,A[K],N;
    clock_t start, end;

    start = clock();

    srand( (unsigned)time( NULL ) );

    A[0] = rand();

    for(j=0;j<K;j++)
    {

    printf("%d\n", A[j]);
    for(i=0;i<=j;i++)
    {

    if (num != A[i])
    {
    num = A[j+1];

    }
    else
    {
    num = rand();

    i = -1;

    }

    }

    }

    end = clock();

    printf("time: %f", (end - start) / CLK_TCK);

    }
  2. #2
  3. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    244
    First, please enclose your code in "code" tags, please see http://forums.devshed.com/misc.php?action=bbcode&s=. Second, run your debugger and see how often i gets incremented to be > j when you keep setting i = -1.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw

IMN logo majestic logo threadwatch logo seochat tools logo