There's an infinite loop.What should I do?

Asked 2 years ago, Updated 2 years ago, 74 views

int main(void) { int i = 0; int arr[10] = { 0 }; int j; int temp;

while (i < 10)
{
    printf("Enter an integer %d >", i);
    scanf_s("%d", &arr[i]);
    for (j = 0; j < i; j++);
    if (arr[i] == arr[j])
    {
        printf ("Duplicated". Please try again");
        i--;
    }
    i++;
}

}

c sorting duplicate-elimination

2022-09-22 18:34

2 Answers

i continues to 0 and repeats indefinitely. If you look at the code one by one...

while (i < 10) // i = 0
{
    printf("Enter an integer %d >", i);
    scanf_s("%d", &arr[i]);

    for (j = 0; j < i; j++); // i = 0, j = 0

    If (arr[i] == arr[j]) // arr[0] == arr[0] so enter if
    {
        printf ("Duplicated". Please try again");
        i--; // i = -1, j = 0
    }
    i++; // Again i = 0, j = 0
} //And i = 0 so repeat above state indefinitely


2022-09-22 18:34

for (j = 0; j < i; j++); Did you mean a semicolon here?

Once you run it, you'll probably start from the beginning

If you look at the order without printf and scanf

while (i < 10)
{
    For (j = 0; j < i; j++); // 0 < 0 so no variable change
    if (arr[i] == arr[j])
    {
        i--;
        i++; 
        //In the end, no variable
    }
}

It's like this.


2022-09-22 18:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.