
Lab
2 — For and While Loops
Due: Sunday, November 9, 2008 at 11:59pm
· To gain practice writing loops
· To be able to design a function given its pre- and post-conditions
Note: don't worry if you can't finish the entire lab exercise. Use turnin (see the last step) to turn in as much as you've completed before you leave the lab. Make sure you finish the rest of the lab on your own time.
1. Sign the attendance sheet.
2. Using emacs or your favorite editor, open a new file named lab2.c. 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.)
3. Compile and run your program. You should get an answer of 3.597740. 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.
4. Modify your program so that it does exactly the same thing, but this time using a for loop.
5. Compile and run your program again. The answer should be the same as before. If you are running out of time, go to the last step. If you have at least 15 minutes left, proceed to step 6.
6. Modify your program to ask the user to provide the number elements of the series to sum. Be sure that your program checks the input for validity; if it is not valid (for example, if the input number is negative), your program should print an error message.
7. Compile and run your program. Test it with several input values and see what it produces. In particular, test it with several small values, zero, a negative value, and several very large values. Construct several other test cases that will produce results that can easily be checked by hand.
8. Turn in your file using the turnin program. The Unix command you should use to submit your files is
/cs/bin/turnin submit cs2301 lab2 lab2.c
See you next week!