CSC 161 Grinnell College Spring, 2009 Imperative Problem Solving and Data Structures

# Laboratory Exercise on Input and Output in C

## Goals

This laboratory exercise provides practice with reading data, computing, and printing within a C program.

## Steps for this Lab

1. Consider the program quarts-1.c from the annotated program in today's reading.

1. Change the printf, so that quarts and liters are printed to 1 decimal-place accuracy.
2. Run the revised program twice, entering 2.44 and 2.47 as the value of quarts. In printing, are these values rounded, or is the value truncated (ignoring the hundreds' digit)?
3. Change the printing, so that quarts is printed in one printf statement and liters in a second printf statement.
2. Write a program that reads a person's weight in pounds and computes (and prints) the weight in grams (1 pound avoirdupois = approximately 453.59 grams).

Run your program with a few test cases. What values might you test (ideally, they should exercise the program's capabilities but be easy for you as programmer to check)?

3. Write a program to read a person's height in feet and inches and print the person's height in centimeters (1 inch = approximately 2.54 centimeters). The output of the program should present an equation of the form:

```   5 feet 6.2 inches = 168.15 centimeters
```

That is, the number of feet should be given as an integer, the number of inches to 1 decimal place, and the number of centimeters to 2 decimal places. One space should separate each number from text or the equal sign.

4. Write a program that reads the radius of a circle and prints the circle's area and circumference in the format illustrated below:

```     radius    area     circumference
2.5    19.63         15.71
```

That is, the radius, area, and circumference should appear under headings, the radius should be printed to 1 decimal place, and the area and circumference to 2 decimal places.

5. Write a program that reads the coefficients a, b, c of a quadratic equation: a x2 + b x + c = 0, and prints the roots of the equation to two decimal places.

Notes:

• Use the quadratic equation (ask the instructor if you have forgotten this).
• For simplicity, you may assume that b2 – 4 a c ≥ 0.
• C's square root function is called sqrt and is defined in C's math.h library.
• To link a C program with the math.h library, your compile command must include the flag -lm. (For example, "gcc -o quadratic quadratic.c -lm".)
6. Do King, Programming Project 3.2 (page 50).

7. Do King, Programming Project 3.4 (page 50).

8. Do King, Programming Project 3.6 (page 51).

This document is available on the World Wide Web as

```     http://www.walker.cs.grinnell.edu/courses/161.sp09/labs/lab-i-o.shtml
```

 created 13 May 1998 last revised 29 January 2009  For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.