go to previous page   go to home page   go to next page

Answer:

You might want to run a program to compute that.

Actually, you would probably use the familiar formula (n*(n+1))/2.


Complete Program

class SumOfIntegers
{
  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. Here is an example run:

C:\>java SumOfIntegers 1 100
Sum from 1 to 100 is: 5050


QUESTION 12:

Would the following method compute the same thing?

  static int sum( int first, int last )
  {
    if ( first==last )
      return first;
    else
      return last + sum ( first, last-1 );
  }