Negative analog value or conversion issue

Hi there, I have a distance sensor and I have been getting weird result when the results are printed.

On occasion, when I put objects in front of the sensor, sometime, the result are displayed in negative value.

As far, as I understand, analogRead() in arduino value are integer positive. Which means I should be getting values from 0 to 1023.
However, when I did sums of value and divide to get the average values, I get negative value.

Here is the following picture and code.

Now, to be honest, the sums of positive value are still positive. And real positive value convert to positive integer should still be positive...
What might cause the issue? I have checked the wiring, and they are well connected...


//Small program calculating the average values, since the noise effect drastically alter value

        int sum;
                  int j=150;    //The number of iteration we want to have
                  int table[150];//Max table size
                  int i=100;
                  int average;
  void setup() {
                //Procedure that calculate the mean value of a matrix
                  void Mean(){
                          //Taking 150 samples with a for loop, every iteration value from the analogRead are saved in a table
                          for (i=1;i<=j;i++){ 
                          //Doing the sum as the iteration goes        
                          //As the loop ended, we divided by 150.                  
void loop() {
     //We want to this test continue, therefore we put this in a void loop

Looks like overflow, 150 x 1023 ~= 150 000, that is more than 32767 max positive N integer can hold.

Hmm, do I have to define the average as integer 32 bit only? Or should I define something for the matrix also?

Thanks for the quick reply :slight_smile:

What is the matrix? Array table? 16-bit o'k