AngryDuck
AngryDuck

Reputation: 4607

how to find the sum of all the values in an int[][] Java?

i have an array of integer arrays 'int pixels[][]'

and i want to find the sum of all of them so i can find the average pixel value

this will be used so that i can set the average value of a pixel to be the threshold value for a pbm image

if the value if above threshold i will export a white pixel if its below i will export a black one (just to give some context)

i assume the code below is not correct at all as the output it 6.0 but i think its something like this

   double threshold = 0;
   for(int i = 0; i < pixels.length; i++)
   {
       threshold += (double)pixels[i][i];
   }
   System.out.print(threshold);

Upvotes: 3

Views: 322

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

you dont need a double when you count sum of ints, this is a waste, use long, it's faster

    long sum = 0;
    int n = 0;
    for (int[] a : pixels) {
        for (int e : a) {
            sum += e;
            n++;
        }
    }
    double avg = ((double) sum) / n;

Upvotes: 0

Rahul
Rahul

Reputation: 45060

You need to use a double for here. Something like this:-

for(int i = 0; i < pixels.length; i++){
        for(int i = 0; i < pixels[i].length; i++){
               threshold += (double)pixels[i][j];
        }
}

Upvotes: 0

Bernhard Barker
Bernhard Barker

Reputation: 55609

You need to iterate over each row and column in the array, so you need 2 for-loops. What you're currently doing only covers the following: (0,0), (1,1), (2,2), ....

This would work: (assuming a non-jagged array, at least for the threshold calculation)

long sum = 0;
for (int i = 0; i < pixels.length; i++)
for (int j = 0; j < pixels[i].length; j++)
{
   sum += pixels[i][j];
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);

Or more simply: (assuming a non-jagged array, at least for the threshold calculation)

long sum = 0;
for (int[] i: pixels)
for (int j: i)
{
   sum += j;
}
double threshold = (double)sum / (pixels.length * pixels[0].length);
System.out.print(threshold);

Upvotes: 0

Mukul Goel
Mukul Goel

Reputation: 8467

HINT

You have a 2D array, So to add each element you need to traverse each column of each row. For this 2 for loops might be of some use.

traverse over each value and add them

exit loop

Divide your sum with number of elements to get average (you may need to give some thought to type casting here)

Upvotes: 0

Jason
Jason

Reputation: 1241

Do you want to iterate all number in arrays,you can try with this:

           double threshold = 0;
           for(int i = 0; i < pixels.length; i++)
           {
               for(int j=0;j<pixels[i].length;j++){
                   threshold += (double)pixels[i][j];
               }
           }
           System.out.print(threshold);

Upvotes: 5

Related Questions