Write a Program Average of Array in Java- Technology369kk

 Average of Array


Program: 

// Q6. WAP where use SUm of Average numbers

class ArrayArray{
    public static void main(String arg[]){
        // define an array
        int[] numbers = new int [] {10,20,30,40,50};

        // calculate sum of all array elements
        int sum =0;
       
        for (int i= 0; i< numbers.length; i++){
            sum = sum + numbers[i];
        }

        // calculate average value
        double average = sum/numbers.length;

        System.out.println("Average value of array elements is:"+average);

    }
}



Explanation :  

  • I am using in this program fast: - sum of natural numbers formal 
The formula for the sum of the first
n
natural numbers is:

                                        Sn=n(n+1)/2

Explanation:

  • Natural numbers: These are the counting numbers starting from 1 (i.e., 1,2,3,,n1, 2, 3, \dots, n).
  • Formula Derivation:
    • If we sum the first nn natural numbers: Sn=1+2+3++nS_n = 1 + 2 + 3 + \dots + n
    • Pairing the terms from start and end: (1+n),(2+(n1)),(3+(n2)),(1 + n), (2 + (n-1)), (3 + (n-2)), \dots Each pair sums to n+1n+1, and there are n2\frac{n}{2} pairs (if nn is even). 
    • If nn is odd, the middle term will be unpaired, but the formula still holds.

Example:

For n=5n = 5:

S5=5(5+1)2=5×62=15S_5 = \frac{5(5+1)}{2} = \frac{5 \times 6}{2} = 15


Verification:-   1+2+3+4+5= 15 


Post a Comment

0 Comments