0

I was writing a program in C to check how many elements in a given array are smaller than or equal to a particular element of same array.

t = no of test cases
n = size of array
k = index of that element array with with whom all the elements have to be compare
j = number of elements less than or equal to element k of array

for (i = 1; i <= t; i++)
{
    scanf("%d", &n);
    scanf("%d", &k);
    for (i = 1; i <= n; i++)
    {
        scanf("%d", &arr[i]);
    }
    for (l = 1; l <= n; l++)
    {
        if (arr[l] <= arr[k])
        {
            j++;
        }
    }
    printf("%d\n", j);
    fflush(stdin);
}

But the problem is that my program is running only for one case. After that it terminates. Why this is happening? Why this is not running for 2, 3, 4 ... test cases?

Swordfish
  • 12,971
  • 3
  • 21
  • 43

1 Answers1

1

You have an outer loop using the variable i and an inner loop also using (and modifying) the same variable i. When the inner loop has completed I assume i is left greater than t so the outer loop also ends. This bug might have been easier to avoid if you had used more meaningful variable names.

Here is your code trimmed down to show the problem:

for (i = 1; i <= t; i++)
{
    for (i = 1; i <= n; i++)
    {
    }
}
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70