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?