Search code examples
cloopsinfinite-loop

Stuck in infinite loop while traversing an array in C


I am trying to run this method that is attempting to determine the amount of numbers in an array that are not repeated and when I am traversing the array, I get stuck in an infinite loop. "Hello" is printed infinitely. Why is this happening?

// function to determine the amount of non repeated numbers
int nonRepeatedNumbers(int arr[], int size)
{
    int i = 0;
    int total = 0;
    printf("%d\n", arr[0]);
    while(i<size-1){
        printf("%s\n", "HEllo");
        total++;
        if (i = 0)
        {
            if (arr[i] != arr[i + 1])
            {
                total++;
            }
        }
        else
        {
            if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1])
            {
                total++;
            }
        }
        i=i+1;
    }
    printf("%d\n", total);
    return total;
}

Solution

  • if (i = 0) Sets i to 0 each time you hit it. Should be if (i == 0)

    You could have found this by printing i and size each time through the loop to see what was going on and why the condition was never met.