28a-section-4-solutions

# 28a-section-4-solutions - CS 106A Handout#28a Solutions to...

This preview shows pages 1–3. Sign up to view the full content.

Handout #28a CS 106A July 23, 2009 Solutions to Section #4 1. Simple arrays /* * File: SieveOfEratosthenes.java * ------------------------------ * This program finds the primes less than UPPER_LIMIT using * the alogorithm called the "sieve of Eratosthenes," which * dates from the 3rd century BCE. */ import acm.program.*; public class SieveOfEratosthenes extends ConsoleProgram { /** Define the upper limit of the search */ private static final int UPPER_LIMIT = 1000; /** Runs the program */ public void run() { boolean[] resolved = new boolean[UPPER_LIMIT + 1]; for (int i = 2; i <= UPPER_LIMIT; i++) { resolved[i] = false; } for (int n = 2; n <= UPPER_LIMIT; n++) { if (!resolved[n]) { println(n); for (int k = n; k <= UPPER_LIMIT; k += n) { resolved[k] = true; } } } } }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
– 2 – 2. Histogram /* * File: Histogram.java * -------------------- * This program reads a list of exam scores, with one score per line. * It then displays a histogram of those scores, divided into the * ranges 0–9, 10–19, 20–29, and so forth, up to the range containing * only the value 100. */ import acm.program.*; public class Histogram extends ConsoleProgram { /** Define the sentinel that signals the end of the input */ private static final int SENTINEL = -1; /** Runs the program */ public void run() { initHistogram(); readScoresIntoHistogram(); printHistogram(); } /** Initializes the histogram array. */
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 4

28a-section-4-solutions - CS 106A Handout#28a Solutions to...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online