2

I'm trying to write a program in C to count the number of positive and negative numbers in an array as well as the number of zeroes.

I have written the following code:

int A[15], pos, neg, nul, i;

[...]

pos = 0;
neg = 0;
nul = 0;

for (i = 0; i <= 15; i++) {
    if (A[i] > 0) {
        pos++;
    }
    if (A[i] < 0) {
        neg++;
    }
    if (A[i] == 0) {
        nul++;
    }
}

However, the counts are always wrong. Specifically, the count for pos and nul is always off by 1. An array of 15 positive numbers and 1 zero gives pos = 16 and neg = 0, while an array of 15 zeroes and 1 positive number gives pos = 0 and nul = 16.

What's going on here and what to do about it?

chqrlie
  • 131,814
  • 10
  • 121
  • 189

3 Answers3

3

Problem:

Your array size is 15 but you traverse it 16 times due to:

for (i=0; i<=15; i++)

Values of i: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}:

A total of 16 indices, where A[15] is undefined behaviour.

Solution:

Change that loop header to:

for (i = 0; i < 15; i++)

This will ensure that the loop runs 15 times with inbound array indices.

Bonus:

An array of n elements is generally traversed as:

for (i = 0; i < n; ++i)
{
    // process a[i] here
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
3

the problem is here for (i=0; i<=15; i++) .You are passing boundaries of your array.

it should be for (i=0; i<15; i++)

hanie
  • 1,863
  • 3
  • 9
  • 19
1

(i=0; i<=15; i++) will pass your arrays boundaries.

Your array size is 15 but since you are starting i from 0 your loop will run 16 times.

The solution is to write it as:

(i=0; i<15; i++)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
qqqqqkks
  • 62
  • 16