Search code examples
javaarraysnumbersaverageoperation

JAVA - Finding the average value of a double type Array - my code doesn't work


My code supposed to do following:

  1. Add up all the double values from this particular array: double nums[] = {10.5, 11.50,12.50,13.50,14.50}

  2. After that it should be divided by 5 or nums.length

All in all I should get 1 result, but my code is showing me nums[i]/5 for each element individually.

Please check my code and tell me, what I did wrong.

public class HelloWorld{

     public static void main(String []args){
        double [] nums = {10.5, 11.50,12.50,13.50,14.50};  
        double result = 0;
        int i;
        for(i=0; i<nums.length;i++){
            result = result+nums[i];
            System.out.println("Average is "+ result/5);
        }
  
     }

}

My current code is displaying following:

Average is 2.1
Average is 4.4
Average is 6.9
Average is 9.6
Average is 12.5

Solution

  • Move the printing line out of the loop so that the average is printed only once.

    for(i=0; i<nums.length;i++){
        result = result+nums[i];        
    }
    
    System.out.println("Average is "+ result/5); // Moved out from the loop body