SumOfOdd - Sum of Odd Integers


Write and save a program SumOfOdd.java that will input a positive integer n and then compute and display the sum of the first n positive odd integers. For example, if n is 5, you should compute 1 + 3 + 5 + 7 + 9. Sample user dialog is as follows:

          Enter a positive integer:
          5
          
          The first 5 positive odd integers are:
          1 3 5 7 9
          
          The sum of the first 5 positive odd integers is:
          25

Here's an algorithm:

          Read n
          
          Compute and print the first n positive odd integers;
          At the same time, compute the sum of the first n
          positive odd integers:
          
          Set sum = 0
          Set currentOddNumber = 1
          Loop n times (a for loop is recommended)
               Print currentOddNumber
               Update sum:
                    Increase sum by the value of currentOddNumber
               Update currentOddnumber:
                    Increase currentOddNumber by 2
          End loop

          Print the sum


The code:

/**
 * SumOfOdd.java
 * Print the first n positive odd integers and their sum.
 */
import java.util.Scanner;

public class SumOfOdd
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      
      // Read n
      System.out.println("Enter a positive integer:");
      int n = in.nextInt();
      
      int sum = 0;
      int currentOddNumber = 1;
      
      System.out.println("The first " + n + " positive odd integers are:");
      
      // Loop n times
      for( int i = 1; i <= n; i++ )
      {
         System.out.print(currentOddNumber + " ");
         
         // Update sum:
         sum = sum + currentOddNumber;
         
         // Update currentOddNumber:
         currentOddNumber = currentOddNumber + 2;
      } // end for
      
      System.out.println("The sum of the first " + n + " positive odd integers is:");
      System.out.println(sum);
      
   } // end main
}