MrStrategschi
MrStrategschi

Reputation: 31

C: Count positive/negative numbers and 0's in array

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?

Upvotes: 2

Views: 1909

Answers (3)

qqqqqkks
qqqqqkks

Reputation: 247

(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++)

Upvotes: 1

Ardent Coder
Ardent Coder

Reputation: 3995

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
}

Upvotes: 3

hanie
hanie

Reputation: 1885

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++)

Upvotes: 3

Related Questions