Lab 3: Arithmetic and Branches

This Lab is divided into three parts. The first two parts require some reading but they are meant to instruct and don't require much programming(although there is some required programming). Take your time with parts 1 and 2 and be sure you understand them. Ask the TA if some part is not clear. Understanding these first sections should make part 3 very easy.

Part 1 Part 2 Part 3

Part 1: Problems with arithmetic

This part of the lab will demonstrate how stupid computers can be. Take the simple math problem:
What is 8 divided by 4
Anyone who has been to a public school should know that the answer is
8 / 4 = 2

Now take the slightly more complicated problem
What is 10 divided by 4 
Most people who have been through public school should know that the answer is
10 / 4 = (2 remainder 2) or 2.5
Now lets see what happens when we use C++ to ask the computer these simple questions.

Ask computer: What's 8 / 4 ?

Compile and run the following program:
#include <iostream>
using namespace std;

int main() {
   cout << (8 / 4) << endl;
   return 0;
}

What does the program print?

Your program run should look like:
-bash-2.05b$ a.out
2
-bash-2.05b$
Which is the correct answer. So far so good.

Ask computer: What's 10 / 4

Modify your code to be:
#include <iostream>
using namespace std;

int main() {
   cout << (10 / 4) << endl;
   return 0;
}

Now what does the program print?

Recompile and verify that the program runs as follows:
-bash-2.05b$ a.out
2
-bash-2.05b$
But that's not the right answer to our problem! As we calculated above
10 / 4
should be
(2 remainder 2) or 2.5

Why is the computer so stupid?

Actually the computer is not really that stupid. It just misunderstands what you are trying to say in C++. It thought you wanted it to print the result of
10 / 4
without printing anything that came after the decimal point. In math and computer science we define something called integer arithmetic. Integer arithmetic simply means that you do your division, addition, multiplication and subtraction just like you normally do but that after you get your result, you effectively set anything past the decimal point to zero. Note this is different from rounding. In integer arithmetic a result of 0.99 is still 0. Hence integer division just takes the result of normal division while ignoring the part that comes after the decimal. In that way the result of
10 / 4 = 2.5 = 2

As normal humans what we are usually more interested in is the value including the part after the decimal point. We want 10 / 4 to result in a value of 2.5. How do we make the computer do this in C++?

Make the computer understand what you want.

Modify the program to the following:
#include <iostream>
using namespace std;

int main() {
   cout << (10.0 / 4) << endl;
   return 0;
}
Now you might think that this would produce the same result because 10 has the same value as 10.0. Try it and see what happens.
Notice how we got the more human answer of 2.5.
In C++ 10.0 is interpreted as what's called a double and any operation(ie + - * /) that is applied to at least one double will use double precision arithmetic. This is more or less what we are used to when we are thinking of arithmetic. More about why this simple change works is discussed in your book. In particular you may want to review section 2.3. For now it's just important to notice how this subtle change of using a decimal point in the value caused a change in the result.

Are computer scientists crazy? Why do we have to go through all this just to divide correctly!

Well actually there is one fairly good reason why there exists both integer division and double precision division. The fact is that computers can do integer division much much (much) faster than they can double precision division. For some applications the integer arithmetic(*, +, -, /) is enough and so the job can be done much much (much) quicker. It's essentially quicker because the computer does not have to use as much logic in dealing with the stuff after the decimal.

Try some more expressions

Now try running the code above again with the following expressions. In each case state what the result would be to a normal human and then give the result that is actually printed by the program. Give a reason why the result does or does not match. Finally give a way to fix the expression so that the precision is the best possible. If nothing needs to be changed, note that as well:
(2 / 3) * 10
(2 / 3) * 10.0
5.5 * 3 + 2
((1.5 * 2) * 10) / 3
the next few are optional extra practice: 5 - 3 + 2
(9 / 10) * 7 * 8.5
(1.0 / 4) * 10
(1 / 4.0) * 10
(1 / 4) * 10.0

So what's the lesson learned?

First we must all remember that computers are helpless without us humans and that without us they're stupid. Second, when you want the division of two constants in C++ to result in an answer that includes a decimal point, you need to have one of those constants include a decimal point. In particular pitfall is that if you use integer division to divide a / b and if a < b then you will always get 0.

Variables, types and precision

Fortunately when you use variables it's clearer what type of arithmetic will be done. Remember integer variables are declared like so:
int i;
The variable i can take on integer values (eg: 1, 2, -1, 4, 2000). Also remember that you declare a variable of type double like so:
double d;
The variable d can take on values like 1.3, 880.3021 8e100 and so on.

Review of Lab 2

From Lab 2 we have the following code:
#include <iostream>
using namespace std;

int main(){
   double first, second;
   cout << "Enter two numbers:" << endl;
   cin >> first >> second;
   cout << first << " / " << second << " = " << first / second << endl;
}
This prints the result of dividing two numbers using double precision division since both first and second are doubles Using your program what is the result of:
6 / 3
7 / 3
99 / 100
999 / 1000

(the rest are optional extra practice)
1 / 2
8 / 9
9 / 3
2 / 3

Notice that the answers are fairly precise.

Integer division using variables

Lets change to integer division. Change the program so that the type of first and second are now both of type int Using your new program what is the result of:
6 / 3
7 / 3
99 / 100
999 / 1000

(the rest are optional extra practice)
1 / 2
8 / 9
9 / 3
2 / 3

Notice that the answers are now less precise because we are using integer division. In particular notice again that all fractions that are less than 1 are evaluated to 0. For instance 8/10 is 80% but to a computer doing integer arithmetic it's just a zero. This particular property can cause many errors in programs(and on tests). Show the TA how the fractions less than 1 evaluate to 0 on your program.

Mixing int and double

Now change the code so that first is an int and second is a double. Using this program what's the result of:
6 / 3
7 / 3
99 / 100
999 / 1000

(the rest are optional extra practice)
1 / 2
8 / 9
9 / 3
2 / 3

Notice that since one of the variables is declared as a double that the computer knows to use double precision arithmetic. In general if at least one of the two variables using (*,/,+,-) is a double then the compiler will produce code that uses double precision arithmetic.

Part 2:

Teaching computers to think: if statements

So far in the labs we have only been doing calculations and basic printouts. This is not much more than what can be done with a $5 calculator. What is the point you may say? Well C++ and computers in general can do more than just crunch numbers. We can ask the computer to do some primitive thinking for us using if statements. Here is an example:
#include <iostream>
using namespace std;

int main(){
   int junk_food;
   cout << "Do you want ding-dongs or ho-hos:(1 for ding-dongs, 0 for ho-hos)" << endl;
   cin >> junk_food;

   if ( junk_food == 1) {
     cout << "Have some ding-dongs!" << endl;
   }

   if ( junk_food == 0) {
     cout << "Have some ho-ho's!" << endl;
   }
   return 0;   
}
In this case the computer actually made a decision as to what to print based on the user input. Notice that the structure of an if statement is fairly close to English. However take particular notice of the == operator. It's different from the = operator which assigns values. The == operator simply checks whether two values are equal. Sometimes it's read "is equal". Compile and run this program.

After this works, modify the cout statements and the variable name to reflect some other choice. There are many choices one can make so you can try to be creative. Your TA may note the funniest/most interesting/wackiest choices and share them with the class(keeping your name anonymous).

After your program runs, take some time to reflect on this moment. By using the if statement(no matter how wacky!) you have actually written a program that can act based on a logical condition. This simple ability is at the heart of what makes computers work. Notice, since we can set the logical condition to anything we want, that computers are still helpless and stupid without us! For instance, we can switch things around so that if one selects hohos we give them ding-dongs. The stupid computer can't tell the difference(ha-ha-ha!). It just follows orders. For extra practice try changing the program around so that hohos are given if ding-dongs are selected and ding-dongs are given if hohos are selected.

if-else

Sometimes when we use if statements we want the computer to do one thing given a certain condition and another thing for all other conditions. To make this easy, C++ has the if-else statement. For instance:
#include <iostream>
#include <string>
using namespace std;

int main(){
  string password; //strings were covered in class
  cout << "What's your password?" << endl;
  cin >> password;

  //the password can't have spaces
  if (password == "blood_sucker") {
    cout << "You typed the correct password.  "
         << "Welcome to Super Evil Enterprizes!" << endl;
  } else {
    cout << "You are human.  We will destroy you!!" << endl;
  }
  return 0;
}

Change the above to some other kind of conditions and show the TA. Note that using if-else statements can simplify the code since you don't have to have two if statements. Also note that this time we are making a simple use of strings.

Combining an if statement and calculations

One can put any valid C++ code in between the curly braces, { }, that follow an if statement. This, combined with the ability to calculate with numbers, allows for very huge complicated programs to be constructed. The next two problems, however, were not designed to be complicated.

Part 3: Programming Exercises.

Exercise 1a

Read Part 1. Compile and run the sample programs as requested. Do the all the problems that are not marked optional (this includes the requested modifications to the sample code). (See Part 1)

Exercise 1b

Read Part 2. Compile and run the sample programs as requested. Do the all the problems that are not marked optional (this includes the requested modifications to sample code). (See Part 2)

Exercise 1c:

(Covered by Part 2) Write a program that outputs whether a student passed or failed an exam. If the exam score is 60 or higher, the student passed. If the score is below 60, the student failed. The exam score should be input by the user and an appropriate message sent to the screen.

HINT: Instead of the == used in Part 2 above, you can use <= (less than or equal to), >=(greater than or equal to), <(strictly less than) and >(strictly greater than).

Exercise 2:

(Covered by Part 1 and Part 2) Write a program that asks the user to choose where they want to go. Let there be two choices, the moon and mars. If they chose mars, ask them for their weight and then output their weight times (377/1000). If they chose the moon ask them for their weight and output their weight times (1/6). Test this with a weight of 100. Remember what was noted about integer division and if statements above. Have the TA check the results and your code.

More Exercises (Optional)

Exercise 3:

In C++, by using a%b you can get the remainder of a divided by b. This is called the modulo operator. Use the modulo operator to print the result of 14 / 4 in terms of a whole number and a remainder. That is, it should correctly calculate
(14 / 4) 
to be
(3 remainder 2)

Exercise 4:

Look up how much someone would weigh on other worlds and add code to let a user chose. For instance on Jupiter your weight would be (318/121) as much as on earth. On a neutron star you would weigh 290,109,600,000 as much as you do on earth. On Io, one of Jupiter's moons, you would weigh 18.35/100 times as much. On Pluto you would weigh 6.7/100 times as much.

Exercise 5:

Allow the user to chose their weight on a certain planet and convert this to earth pounds. Have the computer ask the user something like "Where are you?(1=earth, 2=Pluto etc)" and then ask for their weight. After that, print out their weight on earth. If they weigh more than 1000lbs on earth, suggest that they stay where they are. Also experiment with using strings instead of numbers for the choice selection(as in the password example).



by Anwar Adi