The sum of integers 1 to 100 is Triangle(100)
Actually, you would probably use the familiar
formula 1+2+3+ ... +n = (n*(n+1))/2
.
class SumOfIntegers { public static int sum( int first, int last ) { if ( first==last ) return last; else return first + sum ( first+1, last ); } public static void main ( String[] args ) { int start = Integer.parseInt( args[0] ); int end = Integer.parseInt( args[1] ); System.out.println( "Sum from " + start + " to " + end + " is: " + sum( start, end ) ); } }
Here is a complete program you may want to play with.
The program expects start
and end
to come from the command line. (See Chapter 65.)
Here is an example run:
C:\JavaCode>java SumOfIntegers 50 100 Sum from 50 to 100 is: 3825
In this program, both methods are static
, so you don't need to create an object to invoke sum()
.
Would the following method compute the same thing?
public static int sum( int first, int last ) { return Triangle( last ) - Triangle( first-1 ); }