This lab will develop your skills in using if statements and in calling, designing, and writing functions.
This page will be available as
http://www.tricity.wsu.edu/~bobl/cpts121/lab03_selection/writeup.html
Calling it up in a browser will allow you to cut-and-paste the template below into your editor and save editing time.
Plug your thumbdrive into your workstation. Give it a few seconds to be recognized by Windows and then create a MinGW terminal emulator. In that emulator, create a new directory for this lab and cd to it:
$ cd /e/cpts121 $ mkdir lab03 $ cd lab03
As always, keep all your work in this directory.
One way to compute the area of a triangle with sides a, b, and c, was discovered by Heron of Alexandria around 60 AD. You first compute the semiperimeter:
and the area is then given by
Clearly, s, must be greater than a, b, and c. Otherwise, they would not describe a possible triangle.
In a file heron.c, create a function that implements Heron's formula and a main() function that calls it according to this template:
/*
* Create a function heron() that takes three double arguments, a, b,
* and c. When they describe a possible triangle (e.g. 3, 4, 5), it
* returns its area (which is also a double). When they describe an
* impossible triangle (e.g. 1, 2, 100), it returns -1.0.
*
* The function should proceed in these steps:
*
* 1. If any of the inputs are negative, the triangle is
* impossible. Return -1.0.
*
* 2. Compute the semiperimeter.
*
* 3. If the semiperimeter is less than any of the inputs, the
* triangle is impossible. Return -1.0.
*
* 4. Apply Heron's formula to compute the area of the triangle.
* You'll want to use the sqrt() function in the math library.
*
* 5. Return the area.
*
* Be sure to "#include" any header files you need at the start of the
* file.
*
* Note: At no time should "heron()" include "printf()" calls. If you
* put them there to debug, that's fine but remove them once debugging
* is complete. The lab assistant will check this.
*/
int main(void) {
/*
* main() should do this:
*
* 1. Prompt the user for (doubles) a, b, and c, one prompt per value.
*
* 2. Call heron() to compute the triangle's area. Store the
* result.
*
* 3. If result of heron() is negative, print an "impossible
* triangle" message.
*
* 4. If result of heron() is zero, print a "degenerate triangle" message.
*
* 5. If result of heron() is positive, print the area of the triangle.
*/
return 0;
}
You'll need to compile heron.c with an addition to the command line ("-lm") to include the math library:
$ gcc -Wall heron.c -lm -o heron
Here are some examples of the result:
$ heron
enter a: 7
enter b: 8
enter c: 9
triangle area: 26.832816
$ heron
enter a: 1
enter b: 2
enter c: 3
triangle is degenerate (zero area)
$ heron
enter a: 1
enter b: 2
enter c: 100
error: impossible triangle specified
Show these (or tests like them) to the lab assistant just before you leave.