Ladywithahat Ladywithahat - 1 year ago 81
Java Question

Result = result + [i]?

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);

Sorry if the question is too stupid to ask, but I need to know. why do we have to declare double result = 0?
and why write result = result + nums[i]? why cant we write just result = nums [i]?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download