Lab 3
Deciding What to Do, and Doing it With Style
Introduction
============
Last week we took a deeper look at UNIX, chose sides in the editor
debate, and we wrote our first programs in C++. It was a pretty big
deal, and your head is probably still throbbing from it. I'm sure
you're asking yourself, "What happens next?" with a feeling of both
excitement and dread. What happens next is that we will take a few
small steps toward understanding C++. This week will be a bit
easier, and will give you a chance to catch up if you didn't quite
finish last week.
The reason this week will be easier is that the previous 2 weeks
have consisted of a great deal of "ramp up" which is necessary to
get you started. The learning curve is always a bit steep at first
because there is so much to take in to build a foundation in
computer science. Now that we have a little bit of base skills out
of the way we can build on that. There will be no new Unix
commands, text editors, or tools this week. It's all about further
exploration of the code. This gives you just one thing to focus on.
In this lab we are going to look at simple flow control and text
formatting. This will help us write more useful programs as our
programs will be able to make decisions. Also, our output won't be
so ugly, we are going to learn to format it. Along the way we will
also explore an invaluable reference,
http://www.cplusplus.com.
Part I: Guided by Pythagoras
============================
Journey with me back through the ages to meet with a madman. The
year is 550 BC. The man is Pythagoras of Samos. The place is
Croton, a Greek colony in southern Italy. There, this bearded robed
man set up a religious sect, called the Pythagoreans. He taught
that the universe was governed by order, and he founded the first
school of mathematics to prove it. Its principle teaching was that
everything could be described fully as a set of units; one only must
find what that unit was. For instance, if we observed a square, we
could treat the length of its side as a unit and, therefore, the
perimeter would be 4. Thus 4 was the harmonious whole number of the
square. Pythagoras taught that this was the way the world worked,
and everything was governed by this principle.
Then one fateful morning, one of his disciples came to Pythagoras
and sketched a shape in the sand. The shape looked like this:
|\
| \
| \
|___\
This is, of course, a right triangle. The triangle, whose
Pythagorean number of harmony was 3. The simplest enclosed shape of
straight lines. The student then said to Pythagoras, "Teacher! I
cannot find a unit that matches these sides. Show me the true unit
of this triangle." Pythagoras struggled for days trying to unlock
the base unit of the triangle. He began to become more and more
panicked and more and more distraught as his world view crumbled
around him.
Fortunately, Pythagoras's other students came up with a solution.
They laid hands on the disciple that pointed out the flaw in their
faith, and they drowned him in a well. The problem was solved, and
so they went about finding the units for everything, having thus
established the base line of loyalty of pupils to their teacher's
teachings. (I expect nothing less from each of you.)
The above story is, of course, largely apocryphal. We don't know if
it took place, but we do know that Pythagoras really did struggle
with right triangles in Croton. Eventually, Pythagoras decided to
revisit this triangle and discovered that if he allowed for square
units, he could find the harmony of this vexing triangle. He
sketched an amazing proof of this, which ASCII art can't render
completely. Well, here goes. Emacs, don't fail me now!
Suppose we had 4 right triangles with dimensions a, b, c and we arrange
them in a square as:
#################################
# ### #
# ##### # 2 #
# ####c # b #
# ### b# #
### a # #
#################################
# ## b #
# 2 # ### #
# a # ### c a#
# #a ### #
# # ### #
# # b ###
#################################
Note that we have the areas a^2 and b^2, the remaining area can be
computed by rearranging the 4 triangles (which we can do because
from the above diagram, the square has sides of length a+b):
#################################
# a #### b #
# ### ## #
#b ### ## a#
# ### ### #
# ### 2 ## # 2 2 2
### c ## # Thus a + b = c
## ###
# ## ### #
# ### ## #
#a ## ### b#
# ### ### #
# b #### a #
#################################
Hence, we have proven the pythagorean theorem graphically, using nothing
but ascii art. Pretty cool, huh?
We are going to implement a program which can calculate the sides of
any right triangle. I wanted you to have a little background
though, after all, one of your ancient brethren had to die to bring
you this knowledge.
The three parts of the triangle are the legs (A & B) and the
Hypotenuse (C). Clearly if you know any two of these 3, you know
the other one. Due to the commutativity of addition, we can extract
just two possible formulas for a right triangle. The first is for
when the two legs are known:
________
| 2 2
C= \| A + B (1)
The second is for when only one of the legs, A, is known:
________
| 2 2
B= \| C - A (2)
Design
======
Our program will do the following:
1. Ask the user if they know both legs, or a leg and a hypotenuse.
2. If the legs are known apply formula 1, otherwise apply formula 2.
3. Display the results rounde to two decimal places.
Implementation
==============
1. Create a folder for lab 3 by running: mkdir lab3.
2. Change into the lab3 folder: cd lab3.
3. Using your favorite editor, create pythagoras.cpp and type in
the following code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(void)
{
return 0;
}
4. Notice the #include <cmath> and #include <iomanip> lines? Open
up a web browser and go to
http://www.cplusplus.com and look up
the cmath and iomanip in the reference section. See anything
that could be useful here? There are tons of built in libraries
available to you in C++. cplusplus.com is a great place to
learn about them. Pay particular attention to the following four
items:
* pow
* sqrt
* fixed
* setprecision
After looking at those function's pages and examples, proceed to
step 5.
5. We need to select variables for a, b, and c, as well as a
variable to store the user's choice. Double is the best fit for
the triangle as, unlike what pythagoras originally thought, right
triangles have fractional parts. The user will be entering an
integer to make their selection, and so choice is an int.
Add the following declarations to the appropriate part of the
main function:
double a, b, c;
int choice;
6. Now we need to display the menu to the user. Add the following
lines of code underneath the declarations. (Leave a blank line
for style.) Note that we are also reading the user's choice.
//Get the user's choice
cout << endl << " Triangle Calculator" << endl;
cout << "What do you know about your triangle?" << endl;
cout << " 1.) Both Legs" << endl;
cout << " 2.) A leg and a hypotenuse" << endl;
cout << " Choice? ";
cin >> choice;
7. Now we need to apply the correct formula. Note that there are
just two possibilities, so we are going to use an if..else
structure. Place this code next in the file:
if(choice == 1) {
//apply formula 1
cout << "A=";
cin >> a;
cout << "B=";
cin >> b;
c = sqrt(pow(a, 2) + pow(b, 2));
} else {
//apply formula 2
cout << "A=";
cin >> a;
cout << "C=";
cin >> c;
b = sqrt(pow(c, 2) - pow(a, 2));
}
8. Now we want to display the output to the user. We want to round
everything off to two decimal places. Notice the use of iomanip
functions:
cout << fixed << setprecision(2)
<< "A=" << a << endl
<< "B=" << b << endl
<< "C=" << c << endl;
9. Save the file and then compile it with the following compile line
(from the shell):
g++ pythagoras.cpp -o pythagoras
10. Run the program and try out a few example triangles. When it
works, proceed to part II.
Part II: Improving the Barometer Drop (self lab)
================================================
The professor, angry at the loss of his favorite barometer, was less
than patient when his wayward pupil returned. "You chowder head!
That barometer has been in my family for over 4 generations!", he
said. The boy replied "Sorry, but I was so excited, I also wrote
this program to go with it." Never missing a chance to read good
C++ code (I mean, who would?) he read over the work of
his student.
"Hmmm, this code is good. Not bad for a first attempt." the
professor said. "What do you mean not bad?", the student replied.
"Well, I would prefer if it could solve more aspects of the problem
at hand. For instance, we live in the US, and thanks to the
failings of Jimmy Carter, we still use the imperial system. It
would be nice if it could work in both imperial and SI units.
Also, it would be great if it could predict the number of seconds of
a fall from a given height, as well as the final velocity of the
fall."
The student thought it over for a second and said "Well, it would be
easy enough to store some choice variable about units. But what
about the other parts?" The professor went to the board and wrote
out several formulas in almost legible handwriting. He, of course,
quickly erased them, but our intrepid student captured them! After
all, he knows that you have to be quick on the draw to capture
professorial notes!
1 2
d = --- gt
2
________
| 2d
| ----
t = \| g
v = gt
Also, he noted something about g being different in imperial units
than it is in SI units. Unfortunately, the professor was too quick
with the eraser for him to capture that one. Oh well, that's why
google was invented!
Procedure
---------
We are going to modify your barometer program from lab 2. If you
haven't finished it yet, please take this opportunity to get caught
up. I will still give you credit for it, so long as you get it done
by the end of Tuesday's class. This will be the last such extension!
1. Modify the design of the program from last time to account for
the change in requirements. Below is a sample run to illustrate
how the changed program should behave:
---- begin sample run ----
Will you be working in:
1.) Metric
2.) Imperial
Choice?
What mode will you want?
1.) Height in terms of time.
2.) Time in terms of height
Drop your barometer.
How long was it until you heard a crashing sound (in seconds)? 2.5
Your building is 30.65 meters tall.
The final velocity of the barometer was 24.5 m/s.
Now, you do realize that barometers are filled with mercury,
right? Call the EPA NOW!
---- end sample run ----
Note that the final velocity is always printed, and it should
display the proper units.
Submit your design by the specified due date. Be sure to include
adequate test cases in both metric and imperial units for both
modes of operation.
2. Modify your code to allow for these changes.