## Lab 2 Functions

### Objectives

• To gain practice writing loops
• To be able to design a function given its pre- and post-conditions
• To write a C program that defines and calls a function

Note: don't worry if you can't finish the entire lab exercise. Use turnin (see step 8) to turn in as much as you've completed before you leave the lab. If you don't finish in 50 minutes, you should try to complete the lab on your own time.

### What you should do...

1. Sign the attendance sheet.

2. Using emacs, kwrite, 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 the code that does the summing is inside a function called sumFractions. Here are the pre- and post-conditions for the function:
```PRE:  none
POST: the function returns the sum of the series
1 + 1/2 + 1/3 + ... + 1/20
```
Design a black box for sumFractions (you don't have to submit your black box drawing). Use the black box to help you determine the prototype for the function. Insert the prototype and the function definition in your program. Change the main function so that it calls sumFractions.

5. Compile and run your program. The answer should be the same as before.

6. Add a new function to your program, called sumRange. Here are the pre- and post-conditions for the function:
```PRE:  low and high are positive int's, low <= high
POST: the function returns the sum of the series
1/low + 1/(low+1) + 1/(low+2) + ... + 1/high
```
Design a black box for sumRange. Use the black box to help you determine the prototype for the function. Insert the prototype and the function definition in your program. Change the main function so that it calls sumRange (you will also need to add to the main function statements that prompt the user and accept input values for the function arguments).

7. Compile and run your program. Test it with data values that will produce the same result as the function sumFractions. 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 name of the turnin project is Lab 2.

See you next week!