C++ Exercises

Due before class on Tuesday 9/6


To get yourself acquainted with basic C++, write these three little programs:

The program prime.cpp should input an integer and output whether or not it's prime. A prime number is an integer n > 1 that has no divisors besides n and 1. The simple way to check primality is to try divisors from 2 through the square root of n. Note that there is a break statement in C++, and also that there is a sqrt function in the cmath library.

The program sieve.cpp should output all the prime numbers below 1000. The best way to do this is with a nifty trick called the Sieve of Erastosthenes. Make an array of 1000 booleans to indicate whether each index is prime or not. Assume they're all prime at first, and loop through the array starting at 2. Each time you reach an index that the array says is prime, output it, then loop through all its multiples and change their array entries to indicate that they aren't prime, before continuing on to the next index.

The program swapsort.cpp should define a small array and sort it with a simple swap-based algorithm. The idea behind this algorithm is to loop through the array comparing adjacent entries and swapping them if they're in the wrong order. Repeating this loop n times will sort an array of n entries.


Accomplishments Points
Correct user interaction 5
Correct computation 10
Good style 3

Good style includes:

Handing it in

If you're doing this from a lab computer, you will first need to mount the T-drive by doing this: