Welcome to Week 3! 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?
- If time: 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.
- Pro tip: Look over review exercises from class!
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.
- What are the rules for naming variables?
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
Prompting Users
Activity 5.1: Calculating Your Weight on the Moon (10pts)
- Find a partner for pair programming.
- Open up CodeBlocks.
- The objective of our program is to calculate a user's weight on the moon.
- Create a new C++ file in CodeBlocks and title it moon.cpp.
- Add a block comment at the top of your program with your name and section information.
/*
* Name 1
* Name 2
* Section Info
*/
- Now add a statement to include the iostream library.
- Don't forget to use the standard namespace.
- Create your main function and leave extra space to write your program statements.
- Declare a new variable 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.
cout << "Please enter your weight in pounds: ";
- 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;
- Run your program to calculate your weight on the moon!
- 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
- +/- Decimal Numbers
- Simply put a - sign in front of a number to make it negative
Arithmetic Operators - Add, Subtract, Multiply and Divide - Addition: +
- Subtraction: -
- double difference = 8.1 - 3.9;
- Multiplication: *
- double product = 2.9 * 6.3;
- Division: /
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 My Dear Aunt Sally
Parenthesis
Exponents
Multiplication Division
Addition Subtraction
- To change the order of operations, you use parentheses
- For example:is written as:
a + b / 2 is written as: (a + b) / 2
Notes About Arithmetic- You can use parentheses to group expressions
- Anything within the parentheses is evaluated first
2 * (10 + 5)
- You can have parentheses within parentheses
- Innermost parenthesis evaluated first
(2 * (10 + 5))
- Parentheses cannot be used to indicate multiplication
- Invalid expression:
(2)(3) - Must use the
* operator
Programming Style- Programming style: add spaces around binary operators
- Programming style: no spacing after opening or before closing parenthesis
Mixed-Mode Expressions- Recall that different data types are stored in different forms
- An
int is stored in 4 bytes - A
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
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 CodeBlocks and create a new file called arithmetic.cpp.
- At the top of your program, add a block comment with your names and section information:
/*
* Name 1
* Name 2
* Section Info
*/
- Create starter code like the code below (return 0 is optional):
#include <iostream>
using namespace std;
int main() {
//add your code here
return 0;
}
- Within the curly braces of the
main() function, declare two double variables named a and b , and assign them a value of 7 and2 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
For more information on mathematical functions see the section below. - Save your program source code that displays all eight (8) expressions and submit it to Catalyst.
Completed ProgramOnce you are finished, your source code should look like the following: Mathematical Functions - and a new library
Name | Description | Example | Result |
---|
fabs | absolute value | fabs(-3.9)
fabs(3.9) | 3.9
3.9 | exp | exponent (e^{x}) | exp(1.0) | 2.71828 | log | natural log | log(10.0) | 3.10259 | pow | powers (x^{y}) | pow(2.0, 3.0) | 8 | sqrt | square root | sqrt(4.0) | 2 | sin | sine | sin(0) | 0 | cos | cosine | cos(0) | 1 |
- In addition, the
cmath library includes two similar functions: ceil , and floor
Name | Description | Example | Result |
---|
ceil | ceiling: round up | ceil(3.3)
ceil(3.7) | 4
4 | floor | floor: 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
Group Activity: - Take out your calculator program and add some more calculations to it.
- You should add calculations using at least 3 of the functions above (your choice).
- For example, might add the following:
cout << "pow(a, b) = " << pow(a, b); - When you are finished, find a partner and answer the questions below.
Wrap Up - When finished, answer the questions from today's learning objectives
- With a partner, answer the following questions:
- What will be printed to the console when I run each of the lines of code below:
a1. int result = 7.0 / 2.0; cout << result; 2. double result = 7 / 2.0; cout << 7.0 / 2;3. cout << 7 / 2;4. cout << 7 % 2;5. cout << 9 + 4 * 5 / 2 - 3;
Upcoming Assignments ~See You on Thursday!~ |