Computing the sum of a sequence

 

One of the things you’ve probably encountered in a math class is how to solve the sum of a series of numbers.  Of these, the most common is perhaps: 1, 2, 3, 4, …, n.  What we’re interested in is the sum of the numbers in such a sequence with the last number being n.  This means that for n = 7, we would compute 1+2+3+4+5+6+7.  To write this as a program, we would need to first prompt the user to enter the value of n.  Only then will we be able to construct the sum.  Prompting the user to enter a value is easy:

 

      Scanner input = new Scanner(System.in);

      System.out.print(“Enter the last number in the sequence: “);

      int n = input.nextInt();

 

The last number in our sequence is safely stored in n.  Now before we worry about summing up the numbers, let’s see if we can write some code that produces them all (and prints them).  This would simply be a loop with i’s starting at 1 and ending at n, with an increment of 1 at each iteration:

 

            int i = 1;

      while (i <= n)

      {

            System.out.println(i);

            i++;

      }

 

This will print out the values that i take on, 1 to n.  Now to add up these numbers, we will create another variable called sum to which we add the value of i at every iteration.  When the loop finishes, sum will have accumulated the sum of all the values of i, which is what we want.  Done! Ok, let’s put it together in a class we’ll call SumASequence:

 

import java.util.Scanner;

 

public class SumASequence

{

  public static void main(String[] args)

  {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter the last number in the sequence: ");

    int n = input.nextInt();

  

    int sum = 0;

    int i = 1;

    while (i <= n)

    {

      sum = sum + i;

      i++;

    }

   

    System.out.println("The sum of values from 1 to " + n +

            " is " + sum + ".");

  }

}

 

To check whether our program worked correctly, we can revert to the mathematical knowledge of the solution to such a sequence, which comes out to n(n+1)/2.  Try it out and compare the result to the program’s output.  There’s no need to be disappointed that we’ve put in all this work only to find out that there’s a formula that gives us the answer.  It may be easier to write a program that computes the sum of the sequences in exercise 2 than it would be to derive a formula.