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 natural numbers is:
Sn=n(n+1)/2
Explanation:
- Natural numbers: These are the counting numbers starting from 1 (i.e., ).
- Formula Derivation:
- If we sum the first natural numbers:
- Pairing the terms from start and end: Each pair sums to , and there are pairs (if is even).
- If is odd, the middle term will be unpaired, but the formula still holds.
Example:
For :
Verification:- 1+2+3+4+5= 15
Comments