Search code examples
carrayselementoff-by-one

Count how many times an array element is larger than the subsequent element (off-by-one error)


I'm programming in C. I have to make a function called count , that counts how many times is larger than the subsequent element in the same array. For example, if we had a main code looking like this:

int main() {
    int a1[] = { 5 };
    int a2[] = { 1, 2, 3, 4, 5 };
    int a3[] = { 5, 4, 3, 2, 1 };
    int a4[] = { 1, 9, 3, 7, 5 };
    int a5[] = { 7, 5, 6 };
    printf("%d\n", count(a1, sizeof a1 / sizeof a1[0]));
    printf("%d\n", count(a2, sizeof a2 / sizeof a2[0]));
    printf("%d\n", count(a3, sizeof a3 / sizeof a3[0]));
    printf("%d\n", count(a4, sizeof a4 / sizeof a4[0]));
    printf("%d\n", count(a5, sizeof a5 / sizeof a5[0]));
    return 0;
}

Count should return the following:

0
0
4
2
1

I have tried myself, but it seems like I get an off-by-one error that I don't know how to fix.

int count(int a[], int i){
    int k=0;
    int j;
    for (j=0; j<=i-1; j++){
        if(a[j] > a[j+1])
            k++;
    }
    return k;
}

But this gives this wrong output:

0
1
5
3
2

Can someone spot the mistake in my code, or help me with this?


Solution

  • You're reading a[i] when j=i-1, which is out of array a bound.

    for (j=0; j<=i-1; j++){
      if(a[j] > a[j+1])
    

    It should be

    for (j=0; j<i-1; j++){
      if(a[j] > a[j+1])