class Example {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Writing result = nums [i]
will assign the value of nums[i]
to result
, while writing result = result + nums[i]
will assign the current value of result
plus nums[i]
to result
.
So every time you go around your loop, you're adding the value of nums[i]
to result
, instead of replacing it.
Declaring result = 0
just initialises result
to the value of 0.