11 Jan 2012 [ 201 week1 hw ]

Create a separate class file for each problem, and email all files as attachments to me at jal2016@email.vccs.edu with subject CSC 201 HW2.

Due Thursday, Jan 19.


The infinite sum converges to the mathematical constant the second most important trancendental number. Here ("n factorial") represents the number , so , , , etc.

Write a program (in a class called ExpApprox) that prints the first 20 partial sums (meaning that it prints the sum of the first 1 terms, then the sum of the first 2 terms, ..., on up to the sum of the first 20 terms).

Hints: the 5th sum, for example, can be obtained from the 4th sum just by adding on the next summand (in this case, ). To compute each summand, the 5th summand is obtained from the 4th summand by dividing by 4, and the 6th is obtained from the 5th by dividing by 5, etc. Here's a possible outline:

public class ExpApprox {
    public static void main(String[] args) {
        double term = 1.0;  // current summand
        double sum = 0.0;   // current total
        for (int n = 0; n < 20; n = n + 1) {
            // Update term to current summand value
            // Update sum to the current total
            // Print sum


Write a program (in a class called Age) that asks the user's birthdate, and then prints his or her age.

Hints: you can use the template shown below. The Scanner class can wrap up a more basic object (like the standard input object System.in); it provides a lot of useful methods like nextLine (which returns the next line typed by the user as a String), and nextInt (which returns the next integer typed by the user, as an int). You'll need to decide on the best way to input a birthdate, and how to determine age based on the current date; it's a little trickier than just subtracting years, since you have to worry about months as well.

import java.util.Scanner;
import java.util.Calendar;

public class Age {
    public static void main(String[] args) {
        Calendar now = Calendar.getInstance();
        int currentYear = now.get(Calendar.YEAR);
        int currentMonth = now.get(Calendar.MONTH) + 1;
        int currentDay = now.get(Calendar.DAY_OF_MONTH);
        Scannner input = new Scanner(System.in);
        // Print appropriate prompts, and use input to read birthday.
        // Then determine age based on current date.


Write a program (in a class called Primes) that prints all the prime numbers less than 1000.

Hints: a basic way to test if a number is prime is to check for all possible divisors. To check if x is divisible by d, you can use the modulus operator (%): x % d gives the remainder when x is divided by d.