finding the average of rows of a jagged array

Viewed 44

I am trying to find the average of rows i have on a jagged 2d array I already printed the array out but the average part is printing out the wrong averages. what is wrong with my code?

//print array
for(int k = 0; k < arr.length; k++) { 
    for(int j = 0; j < arr[k].length; j++) {

        System.out.print(arr[k][j] + " ");             
    }

    System.out.println();
}
          
//average
for (int r = 0; r < arr.length; r++) {
    double sum = 0.0;
    double avg = 0.0;
    for (int c = 0; c < arr[r].length; c++) {
        sum += arr[r][c];  
        avg = sum / i; // i is the columns of the array;
    }
   
    System.out.println("Row " + (row + 1) + " average is: " + avg);
    
}
1 Answers

Rather than working out the average on the fly you should calculate it at the end only by moving avg = sum / i; outside of the nested loop otherwise it will divide by an incorrect every time it loops. Also use avg = sum / arr[r].length; instead because we know exactly how many columns each row has:

    for (int r = 0; r < arr.length; r++){
        double sum = 0.0;
        for (int c = 0; c < arr[r].length; c++){
            sum += arr[r][c];  
        }
        //Calculate the average outside the nested loop using (sum / columns)
        double avg = avg = sum / arr[r].length;
        System.out.println("Row " + (row + 1) + " average is: " + avg);
    }
Related