## Welcome to Lesson 5!

### Learning Objectives of Today's Lesson

• What is the cin object and how do you use it?
• What are the three necessary components of a complete interaction with a user of your program?
• What are the 5 arithmetic operators in C++?
• What is modulus (%) and why is it necessary?
• What is the difference between integer and floating point division?
• What is the cmath library and what are some of the operations it can perform?

## Announcements

• Return Quiz 1 after break
• Quiz 2 on Thursday
• 6 questions
• 3 repeat questions from Quiz 1
• Material through today's lesson.
• Practice quiz? Look over review exercises from class!
• Don't forget to do Lab 3 on the CodeLab website!

## Review Exercises

Find a partner and answer the following questions.

Part 1:
• What are the four most common data types that we will be using in this class? Give an example of each.
• Which of the following are correct examples of declaring a variable and assigning it a value?
• Int numCats = 5;
• double tempInF = 98.6;
• double distance_to_school = 5 miles;
• bool 2coolForYou = false;
• char myInitials5 = 'A';
• boolean loveCode? = True;
• char letters = 'XYZ';
• int studentId;
studentId= 555555;
• int studentId;
55555 = studentId;

Part 2:

What Gets Printed to the Screen?

//assume below statement are part of a main function

int oranges = 5;

int apples = 3;

int numFruit = apples + oranges;

cout << "Total Fruit: " << numFruit << endl;

apples = apples - 2;

oranges = apples;

cout << "Apples: " << apples << endl;

cout << "Oranges: " << oranges << endl;

## Input and Output Cont'd

• Another way to enter data into a variable is to read it from the console
• The input console (keyboard) is called `cin` (console input)
• We use the `>>` operator with `cin` to send data to a variable
• For example:
`cin >> numberOfDragons;`
• In this example, whatever valid integer number the user types is stored in the variable `numberOfDragons`

### Output Using `cout`

• `cout` sends data to standard output, which is usually the terminal (console) window
• The "`<<`" takes data from the right-hand side and sends it to the console
• Any data can be output to the console
• Variables
• Literals
• Expressions (which can include all of above)
• We can display multiple values in one `cout`
• Each data item must be separated with a `<<` operator
• For example:
```int numberOfGames = 12;
cout << numberOfGames << " games played." << endl;
```
• Three values are output:
• The value of the variable `numberOfGames`
• A literal string "` games played.`"
• An end-of-line (newline) character
• In the above example `endl` is a special word for an end-of-line (newline) character
• A second way to output an end-of-line (newline) is to use '`\n`'
• For example:
```int numberOfGames = 12;
cout << numberOfGames << " games played.\n";
```

### Prompting Users

• Good programming practice is to always "prompt" users for input like:
```cout << "Enter number of dragons: ";
int numberOfDragons;
cin >> numberOfDragons;
cout << "You entered " << numberOfDragons
<< " dragons\n";
```
• Note that we do not put a newline after the prompt
• The prompt waits on the same line for keyboard input as follows:
`Enter number of dragons: _`
• Where the underscore above denotes where keyboard entry is made
• Every `cin` should have a `cout` prompt before it

## Activity 5.1: Calculating Your Weight on the Moon (10pts)

• The objective of our program is to calculate a user's weight on the moon.
• Find a partner and open up Eclipse.
• Create a new C++ project named Moon with a file named moon.cpp.
• Alter the block comment at the top of your program to include your name, your partner's name and the section information.
/*
* Name 1
* Name 2
* Section Info
*/
• Declare a new variable at the top of main to capture the user's weight. Name your variable weight.
• What data type do we need here? Why?
• Place your variable between the curly braces of the main function.
• Now, let's output a message to the screen explaining to the user the purpose of our program. What command do we use here?
cout << "Welcome! Let's calculate your weight on the moon!\n";
• Run your program to make sure it works and you get the output you expected.
• Now, we need another cout statement to prompt the user to enter his or her weight. Add this statement right below the lastcout statement.
• Make sure that you have left a space right before the second set of quotation marks to allow space for the user to type his or her answer.
• Now, run your program again to ensure you haven't made any errors.
• Next, we need to add a cin statement to capture the user input and store it in the weight variable. Be careful when typing the arrows that they are pointing in the correct direction (towards the variable).
cin >> weight;

• Using the weight entered by the user, we need to calculate the user's weight on the moon. To calculate his or her weight on the moon, we divide his or her weight on earth by 6. Write the following statement:
weight = weight / 6;

• Finally, we need to display our results to the user. Add a new cout statement like the one below:
cout << "Your weight on the moon is: " << weight << endl;

• Submit your activity to Catalyst when you are finished. Note: Both partners need to submit for full credit.

## Arithmetic Operators and Expressions

### How Do You Represent Negative and Positive Numbers in C++?

• +/- Integers
• -123456
• 123456
• +/- Decimal Numbers
• -12345.678
• 12345.678
• Simply put a - sign in front of a number to make it negative

### Arithmetic Operators - Add, Subtract, Multiply and Divide

• int sum = 5 + 6;
• Subtraction: -
• double difference = 8.1 - 3.9;
• Multiplication: *
• double product = 2.9 * 6.3;
• Division: /
• int quotient = 6 / 2;

### But, wait! There's one more operator... Introducing modulus...

• Modulus: %
• The remainder when you divide.
• Represented as the % sign.
• Counter-part to integer division.
• int remainder = 12 % 5;

### Order of Operations

• Remember PEMDAS from your math classes? Please Excuse MDear Aunt Sally
Parenthesis
Exponents
Multiplication
Division
Subtraction
• To change the order of operations, you use parentheses
• For example:
is written as: `a + b / 2`
is written as: `(a + b) / 2`

1. You can use parentheses to group expressions
• Anything within the parentheses is evaluated first
`2 * (10 + 5)`
2. You can have parentheses within parentheses
• Innermost parenthesis evaluated first
`(2 * (10 + 5))`
3. Parentheses cannot be used to indicate multiplication
• Invalid expression: `(2)(3)`
• Must use the `*` operator

### Programming Style

• Programming style: add spaces around binary operators
• `2 + 3`, not `2+3`
• Programming style: no spacing after opening or before closing parenthesis
• `(2 / 3)`, not `( 2/3 )`

### Mixed-Mode Expressions

• Recall that different data types are stored in different forms
• An `int` is stored in 4 bytes
• `double` is stored in 8 bytes
• The format they are stored in is different as well
• The computer needs both operands in the same form before it can perform an operation
• If one operand is different than the other, the compiler converts it to the wider of the two types
• For example:
`2 + 2.3`
• First number (`2`) is an `int`
• Second number (`2.3`) is a `double`
• C++ will automatically convert an `int` to a `double`
• Then the arithmetic operation can take place to produce a result of `4.3`
• Remember that the result of arithmetic with an `int` and a `double` is a `double`

### Integer Division and Modulus

• Dividing two integers can produce unexpected results for the unwary
• In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
```7.0 / 2.0   // 3.5
7 / 2.0     // 3.5
7.0 / 2     // 3.5
```
• However, if both numbers are integers, then the result is an integer:
```7 / 2       // 3
```
• The decimal remainder is truncated (cut short, discarded, thrown away)
• To get the integer remainder of division between two integers, you use the modulus operator: %
```7 % 2       // 1 (remainder)
```
• `7 % 2` returns `1` because `1` is the remainder when `7` is divided by `2`:
```    3  r 1
2 ) 7
-6
1 remainder ```

## Mathematical Functions - and a new library

• Operators provide only the simplest mathematical operations
• For more complex operations, we use mathematical functions
• A C++ function is like a mathematical function that takes an argument ("input") and produces ("returns") a value
• For example:
`cout << sqrt(9.0) << endl;`
• In the above example, the input is `9.0` and the `sqrt()` function returns the square root of the argument
• C++ has a standard library named cmath that contains many such functions
• Some of the functions are listed below
• Note that many of these functions are designed to work with floating-point date types like `double`
NameDescriptionExampleResult
fabsabsolute value`fabs(-3.9)`
`fabs(3.9)`
`3.9`
`3.9`
expexponent (ex)`exp(1.0)``2.71828`
lognatural log`log(10.0)``3.10259`
powpowers (xy)`pow(2.0, 3.0)``8`
sqrtsquare root`sqrt(4.0)``2`
sinsine`sin(0)``0`
coscosine`cos(0)``1`
• In addition, the `cmath` library includes two similar functions: `ceil`, and `floor`
NameDescriptionExampleResult
ceilceiling: round up`ceil(3.3)`
`ceil(3.7)`
`4`
`4`
floorfloor: round down`floor(3.3)`
`floor(3.7)`
`3`
`3`
• Both return whole numbers, although they are of type `double`
• Why might this be the case?

### Using Mathematical Functions

• How are mathematical functions evaluated?
• Whatever is within the parenthesis of the function call is evaluated first
• Thus, in the following example, we get the square root of `9.0`
`cout << sqrt(3.0 * 3) << endl;`
• If the function is used in an arithmetic expression, they are handled just like a number of the type returned
• For example, in the following, the value `4.0` is stored in the double variable `num`:
```double num = 1 + sqrt(3.0 * 3.0);
cout << num << endl;
```
• Note that the function evaluates the `sqrt(3.0 * 3)` before adding it to `1.0`
• Thus functions have a higher precedence than arithmetic operators.

## Activity 5.2: Arithmetic (10 pts)

Through the miracles of computer science, we will now convert your \$1000 computer into a \$10 calculator! Along the way, we learn how to work with arithmetic using C++.

#### Specifications

• Find a partner for pair programming.
• Open up Eclipse and create a new project called Arithmetic with a file named arithmetic.cpp.
• At the top of your program, add a block comment with your names and section information:
/*
* Name 1
* Name 2
* Section Info
*/

• Within the curly braces of the `main()` function, declare two `double` variables named `a` and `b`, and assign them a value of `7` and`2` respectively. For instance:
`double a = 7, b = 2;`
• Add a line of code to display the arithmetic expression `(a + b)` and then recompile and run the program.
```cout << "a + b = " << a + b << endl;
```

The output when you run the program should look like this:

```a + b = 9
```

If you do not see this output, please ask a classmate or the instructor for help.

• Add three more lines of code like the previous one that computes the expressions: `a - b``a * b` and `a / b`. Compile and run your program again and make sure your program now displays the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
```
• The order of operations matters in C++ just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:
```cout << "a + b / 2 = " << a + b / 2 << endl;
cout << "(a + b) / 2 = " << (a + b) / 2 << endl;
```
• Compile and run your program again and compare the output. Your program should now display the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
a + b / 2 = 8
(a + b) / 2 = 4.5
```

Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra.

As you can see, arithmetic in C++ works much like you would expect. However, there are some mysteries when working with integer variables which we will now explore:

• Truncation in integer division
• Modulus (%) operator

• Truncation in integer division: Change the data type of the two variables from `double` to `int`, like this:
`int a = 7, b = 2;`
• Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?

In programming terms, we say that the decimal part is truncated (cut short). You have to watch out for this in C++ programming or you may get unexpected results in your calculations.

• Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statement to your program:
```cout << "a % b = " << a % b << endl;
```
• Compile and run your program again with this added statement. Your program should now display the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1```
• Mathematical functions: More complex mathematical operations require the use of a function in C++. one such function is `sqrt(number)` which calculates the square root of the number inside the parenthesis. Add the following statement to your program:
```cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
```
• You program will not compile with this new statement because you must include a library of the mathematical functions. Add the statement: `#include <cmath>` to the top of your program like this:
```#include <iostream>
#include <cmath> // math function library
using namespace std;
```
• Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1
sqrt(a + b) = 3
```

• Save your program source code that displays all eight (8) expressions and submit it to Catalyst.

### Completed Program

Once you are finished, your source code should look like the following:

## Wrap Up

• When finished, answer the questions from today's learning objectives
• With a partner, answer the following questions:

### 6. cout << 9 + 3 * 5 / 2 - 3;

Upcoming Assignments

~See You Monday!~