Computer Science 202
Introduction to Programming
Fall 2012, The College of Saint Rose
Sum2ToNBy2 BlueJ Project
Click here to download a BlueJ project for Sum2ToNBy2.
Sum2ToNBy2 Source Code
The Java source code for Sum2ToNBy2 is below. Click on a file name to download it.
/* * Example Sum2ToNBy2: sum the even integers from 2 to some specified upper limt * * Jim Teresco, The College of Saint Rose, CSC 202, Fall 2012 * * $Id: Sum2ToNBy2.java 1937 2012-10-08 18:06:13Z terescoj $ */ import java.util.Scanner; public class Sum2ToNBy2 { public static void main(String[] args) { // we'll read the upper limit from the keyboard Scanner keyboard = new Scanner(System.in); // the upper limit should be an even number greater than 0 int upperLimit = 0; while (upperLimit <= 0 || upperLimit % 2 != 0) { System.out.print("Enter an even positive integer for the upper limit of our sum: "); upperLimit = keyboard.nextInt(); if (upperLimit <= 0) { System.out.println("Make it positive!"); } else if (upperLimit % 2 != 0) { System.out.println("Make it even!"); } } // now we are ready to compute the sum // initialize to 0 to start int sum = 0; // count by 2's up to our limit: // notice we are initializing our number to 2, we continue // as long as number is less than or equal to the // upper limit, and we add 2 to the number each time around // using our += shorthand notation for number = number + 2 for (int number = 2; number <= upperLimit; number += 2) { // shorthand to add number to sum sum += number; } // and print our result System.out.println("Our sum is " + sum); } }