// This program uses a function to sum up the sequence
// of integers from 1 to 10
class Sum2 {
public static void main(String[] args) {
System.out.println( sum(10) );
}
//Sum up integers from 1 to N.
// assume N > 0
static int sum(int N) {
int total=0;
for (int i=1; i<=10; i++) {
total += i;
}
return total;
}
}
|
This version has a number of small changes that make it look a
little more like a real Java programmer would write it.
- Rather than creating a variable to hold the value returned by
the sum() function, I just put the call to sum
directly into the call to System.out.println().
- Down in the sum function, I used the increment
operator, '++'. Adding '1' to a variable (incrementing
it) is so common, many languages (C/C++, Java, Perl, Python, PHP
to name a few) use this operator as a sort of abbreviation. Using
this operator allows me to write i=i+1 as simply
i++.
- Another operator was introduced to allow incrementing a
variable by a number other than one. This is what '+='
does. This let me write total=total+i as total+=i.
Similarly, there are a number of other operators that do this kind
of thing like '*=' which means multiply the variable on
the left side by the number on the right side so that something
like a = a * 3 would be written
a *= 3.
|