CS1005 - Term C, 2003
Laboratory 2
January 22, 2003
Purpose
The goal of this lab is to give you practice in writing a
program that uses looping and selection structures.
What you should do...
- Sign the attendance sheet.
- Using emacs, open a new file named lab2.cxx to contain your program.
- Using a while loop, write a program that will calculate and print the sum of the
following series:
1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + ... + 1/20
(Hints: This is a summing loop, so you need to set your summing variable to
0. This is also a count-controlled loop; set up the loop so that it will
execute 20 times.
- Compile and run your program. You should get an answer of 3.59774
. If your program does not display the correct answer, see if you can
find the error(s). Remember to save your file after making any changes,
and re-compile before you try to run the program again. If you are
running out of time, skip ahead to step 7. If you have at least 15 minutes
left, proceed to step 5.
- Now modify your program so that it calculates and prints the
following sum instead:
1 + 1/2 + 1/4 + 1/5 + 1/7 + 1/8 + 1/10 + ... + 1/20
Notice that this time terms in which the denominator is a multiple of 3 are not included in the sum. (Hint:
an if statement inside the loop will make the final
decision as to whether or not to include a given term in the sum. )
- Compile and run your program. This time the answer should be 2.78107.
- Use the `script' command to record a sample run of your program. Your
script file should be named lab2.script.
- Turn in the `.cxx' file and your script file, using the turnin program. Use
the following command at the UNIX prompt:
/cs/bin/turnin submit cs1005 lab2 lab2.cxx lab2.script
Glynis Hamel
2003-01-16