`hellome.cpp` ".g++ -Wall -Wextra -Wpedantic -std=c++11 -o hellome hellome.cpp If you have problems, ask a classmate or the instructor for help as needed. $ ./hellome Hello, World! Hello, Ed Parrish! `/**` and ends with `*/` is known as a block comment. Comments are parts of code that are ignored by the compiler. Delete the entire block comment and then recompile and rerun your code.You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed. } // end of main functionThe last part of the line is another type of comment that starts with `//` and lasts until the end of the line. Delete the comment and then recompile and rerun your code.You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed. `using namespace std;` and then try to recompile the code.Your program should not compile and you should get an error message. If you have a different experience, ask a classmate or the instructor for help as needed. `using namespace std;` back into your program and verify that it compiles.If you have problems, ask a classmate or the instructor for help as needed. When finished, move on to Part B. ## Specifications Part B: Reflection (3m)- Create a second text file named "
**syntax.txt**" and record your answers to the following questions:- Does a comment change the way that a program compiles or runs?
- What error message does the compiler report when you leave out the following command?
using namespace std;
- Submit both your
`hellome.cpp` and`syntax.txt` files to Canvas Exercise 2.1.
When finished, please help those around you. ## 2.1.7: Summary- C++ has two styles of comments:
`//` `/* ... */`
- Comments help document what a program does:
- Use block comments at beginning of a file and before functions
- Otherwise, use comments them sparingly
- Statements are the commands we give a computer in a program
- C++ has standard libraries of prewritten code
- Definitions for these libraries are collected in a namespace called:
`std` - Thus, most of our programs will begin with two declarations:
#include <iostream> using namespace std; - Every C++ application starts with a function named
`main()`
## Self ReflectionAnswer these questions to check your understanding. If you are not sure, then review the material above. - What is the purpose of a comment?
- What styles of comments are allowed in C++?
- What is a statement?
- How can you tell which lines of a program are statements?
- What statement do you use to print a message to the console window?
- What is meant by the term "whitespace"?
- Where does every C++ program start?
- What code do you write for the
`main()` function? - How do you include libraries in your C++ programs?
## 2.2: Memory Concepts## 2.2.1: Importance of Memory- Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
- We can store our friend's phone number in our memory
- We even give our friend's phone number a label, like "Grace's phone number"
- We do not really know where in our brain we store Grace's phone number
- However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368
- Just like we store our friend's number in our memory, we can store it in a computer's memory
- We store data in a computer program using a
*variable*variable: the name of a place to store data in a computer's memory - Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
- We simply give it a name and let the compiler decide where to store the data
## Why Data Matters- Why should we care about variables or storing data?
- Variables are the most important part of any computer program
- Just like in real life, it is hard to do anything without memory
- Consider a simple algorithm like adding two numbers:
- Get the first number
- Get the second number
- Add the first and second number and assign it to sum
- Display that
`sum` is the result
- How many variables did we need for this algorithm?
- To find out, let us do some role playing
- Imagine a conversation between Hal and Grace:
- After Grace says, "2", Hal has to store the number in his memory
- The same things happens with the number, "3"
- Even if the numbers were given in the same sentence, Hal would have to store the numbers somewhere in his memory
- After adding the two numbers together, Hal has to store the result of the addition, at least temporarily, so he can state the answer
- If we were to write a program to add two numbers together, the computer would have to use memory just like Hal
## Check Yourself- The name of a location to store data in a computer's memory is known as a(n) ________.
- True or false: remembering data is rarely important when processing information.
- To add two numbers, we need to store at least ________ pieces of information.
- 0
- 1
- 2
- 3
## 2.2.2: Introduction to Variables- Recall how a computer is organized
- Main memory is organized as a long list of memory locations
- Each location stores one byte and is identified by an address number
- 1 gigabyte (GB) is about 1 billion bytes
In RAM memory terms, 1 GB is 230, 10243 or 1,073,741,824 bytes
## Storing Data- The main feature that separates computers from other machines is memory
- To store and retrieve data in a program we use a variable
- A variable is a name for a location in a computer's memory
## Variable Declaration- Here is an example C++ variable declaration:
int num1; - When we declare a variable we tell the computer to set aside space to store data in its memory
- Notice that a variable declaration has two parts:
**int**: the type of data the variable will store, integer values in this case**num1**: the name of the variable, which we make up while coding
- Variable names are a sequence of letters, numbers and the underscore (
`_` ) - However, variable names cannot start with a number and cannot contain spaces
## Data Types- Like human memory, a computer must encode information before storage
- As programmers we tell the computer how to encode information using data types
- A commonly used numerical data type is
`int` , which is shorthand for integer**int**num1; - An
`int` specifies a whole number with no fractions or decimal points - If we want to store numbers with a decimal point, we use a floating point type like
`double` **double**pi;
## Some Commonly Used Numerical Data Types
## Assignment- After we declare a variable, we must assign the variable a value
- To assign values, we use an assignment operator, which is an "equals sign" (
`=` ) - The assignment is made in an assignment statement in this form:
*variable*=*expression*; - Where:
*variable*: the name of the variables*expression*: the data we want to store in the variable
- An assignment statement assigns the value of
*expression*(right side) to the*variable*(left side) - Examples:
int num1; // variable declaration num1 = 45; // assignment int num2 = 12; // declaration + assignment int total = num1 + num2; // more complex expression - Notice that we can combine variable declaration with assignment
- Good programming practice says we should assign a value when we declare a variable
- Otherwise the value is undefined, though often 0, until the variable is assigned a value
## Variables by Analogy- We can think of variables as boxes made of computer memory
- A variable is just like a box that can hold a single thing
- We need a way to tell one box from another so we give it a name
- As we discussed, we can make up almost any name we want for the variable
- For example, we declare a variable "
`a` "int a; - When we first declare a variable the box is empty but has a name
- Storing values in a variable is like putting items in a box
- For example, we assign the variable "a" the value
`1` a = 1; - We can think of the above statement as putting the value
`1` in a box with the variable name "`a` ", like the one shown below (images source: David Goodger) - We put names on a box
- We put values inside of boxes
- When we want to see the value inside a box we look at it with code like:
cout << a << "\n"; - If we change the value of a variable, we are putting a new value in the same box, like:
a = 2; - Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
int b = a; - We now have two different boxes that have independent values
## Try It: Code Variables (2m)- Start your text editor and open the
**hellome.cpp**from the last exercise. - Inside the curly braces of
`main()` , declare an integer variable named "`favNum` " and assign it the value of your favorite number, like:int favNum = 42; - After displaying your name, print the value of your favorite number like:
cout << "Your favorite number is " << favNum << ".\n"; - Compile and run the code and verify your program shows output like the following:
Hello, Ed Parrish! Your favorite number is 42.
When finished, please help those around you. ## Check Yourself- The name of a location to store data in a computer's memory is known as a(n) ________.
- To specify the type of data stored in a variable, variable declarations include a(n) ________ ________.
- True or false: the "equals sign" (=) is the assignment operator in C++.
- The following code prints the value ________.
int x = 42; cout << x << "\n"; - After executing the following statement, the value of
`number` is ________.int number;
## 2.2.3: Input and Output- Recall the main parts of a computer
- Input sends information to the computer
- Output is the computer sending information
- We now review these parts starting with output
## Output- We have been using
`cout` to display information on our video monitors - The command
`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 consolecout << "Hello, World!\n"; - Most basic data can be output to the console including
- Variables (like
`num1` ) - Literals (like
`12.34` ) - Expressions (which can include all of above)
- Variables (like
- We can display multiple values in one
`cout` - However, each data item must be separated with a
`<<` operator - For example:
int numberOfDragons = 3; cout << numberOfDragons << " dragons." << endl; - Three values are output in order:
- The value of the variable
`numberOfDragons` - A literal string "
`dragons.` " - An end-of-line (newline) character
- The value of the variable
- In the above example
`endl` is a special word for an end-of-line (newline) character - Notice that the last letter of
`endl` is an "el" and not a one - Another way to output an end-of-line (newline) is to use "
`\n` " - For example:
int numberOfDragons = 3; cout << numberOfDragons << " dragons.\n";
## User Input- So far we have used an assignment operator "=" to assign a value to a variable
int numberOfDragons = 3; - Another way to assign a value to a variable is to read it from the console
- The keyboard input console is called
`cin` (**c**onsole**in**put) - 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`
## 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 like:
`Enter number of dragons: _` - Where the underbar above denotes where keyboard entry is made
- Every
`cin` should have a`cout` prompt before it
## Check Yourself- The following code displays ________.
int numberOfGames = 12; cout << numberOfGames << " games played.\n"; - Before getting input from a user, common practice is to display a(n) ________.
- True or false: the << and >> always point in the direction the data is flowing.
## Exercise 2.2: Adding Two Numbers (8m)In this exercise we will write a program to add two numbers together. When it runs, the program acts like this: Enter the first number: 2 Enter the second number: 3 The sum of 2 and 3 is 5. I suggest that you compile after each step so you know where an error is located if you make a mistake. ## Specifications- Copy the following program into a text editor, save it as
, and then compile and run the starter program to make sure you copied it correctly.**variables.cpp**#include <iostream> using namespace std; int main() { // Enter your code here return 0; } - In
`main()` , declare an`int` variable named`num1` and assign it a value of`0` :int num1 = 0; For more information on declaring variables, see section: 2.2.2: Introduction to Variables - Add code to display a prompt to the screen:
cout << "Enter the first number: "; For more information on prompting users, see section: 2.2.5: Input and Output - Add a statement to input a new value for the variable and store it in memory:
cin >> num1; For more information on reading data from users, see section: 2.2.5: Input and Output - Declare a second variable of type
`double` named`num2` and assign it a value of 0.0:double num2 = 0.0; For more information on data types, including the `double` data types, see section: 2.2.4: More About Data Types - Add code to display a prompt to the user: Enter the second number:
- Add a statement to get the second number from the user variable and put it into num2.
- Declare a third variable of type double named
`total` and assign it the result of adding the two variable together:double total = num1 + num2; - Write another statement that displays the result of adding the two numbers together:
cout << "The sum of " << num1 << " and " << num2 << " is " << total << ".\n"; - Compile and run your program to make sure it works correctly.
- Submit your program file variables.cpp to Canvas in Exercise 2.2.
When finished, please help those around you. ## 2.2.4: Summary- Variables are how we can store data in our programs
- Variables must be declared before use like:
int x; - Once declared, we can assign a value to the variable like:
x = 42; - Simple assignment statements have a variable, equals sign and an expression:
variable = expression;
## User Input- Another way to store data in a variable is to read it from the console
`cin` is an input stream bringing data from the keyboard- The '
`>>` ' points toward where the data goes - When designing I/O:
- Prompt the user for input
- Echo the input by displaying what was input
`cout` is an output stream sending data to the monitor- The insertion operator "
`<<` " inserts data into`cout` - There are two ways to output a newline character:
cout << "Hello World!\n"; cout << "Hello World!" << endl;
## Self ReflectionAnswer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material. - Why do you need to store data when creating a program? (2.2.1)
- How do you store information in a computer's main memory? (2.2.2)
- What code would you write to declare an
`int` variable named`foo` and assign it a value of`10` ? (2.2.2) - What code would you write to display a variable named
`foo` to standard output? (2.2.3) - What code would you write to input data from the keyboard and store it in a variable named
`foo` ? (2.2.3) - Why is it a good practice to prompt users before input? (2.2.3)
- What are two ways to assign a value to a variable? (2.2.3)
## 2.3: Numbers and Arithmetic## 2.3.1: Computations Using Numbers and Arithmetic- Many problems can be solved using mathematical formulas and numbers
- Consider the simple problem of adding up all the coins in a pocket to get the total value in dollars
- If we know the number of each coin type what would be the formula to calculate the dollar value?
int pennies = 8; int nickels = 5; int dimes = 4; int quarters = 3; - To implement this formula, we will need to use numbers and arithmetic
- Remember that C++ has two general types of numbers: integers and floating-point
## Integers- An integer number is zero or any positive or negative number without a decimal point
- Examples of integers include:
0 1 -1 +5 -27 1000 -128 - We call plain numbers like these literal integers because they stand for what they look like
- By comparison, a variable may contain an integer but is not a literal integer
- Literal numbers are constant and do not change while a program executes
- Integers are usually stored in stored in four (4) bytes of computer memory
## Floating-Point Value- A floating-point number is any signed or unsigned number with a decimal point
- A floating point number approximates a real number and has a trade-off between range and precision
- For example:
0.0 1.0 -1.1 +5. -6.3 3234.56 0.33 - Note that
`0.0` ,`1.0` and`+5.` are floating-point numbers, but could be rewritten as integers - In C++, both integers and floating-point numbers cannot have any commas or special symbols
- Floating-point numbers are usually stored in stored in eight (8) bytes of computer memory
## Program coins.cpp to Sum Coins
## Check Yourself- The two types of numbers in C++ are ________ and ________.
- Of the following literal numbers, the single integer is ________.
`1` `1.2` `1.23` `1.234`
- For the following code, the literal number is ________.
int pennies = 8;
## 2.3.2: Arithmetic- C++ uses the following operators for arithmetic:
- + for addition
- - for subtraction
- * for multiplication
- / for division
- % for modulus (remainder after integer division)
- Modulus is a type of division operation for integer numbers
- The first four operators should be familiar and we will discuss modulus (
`%` ) today
## Precedence Rules- Precedence: what gets done first
- Arithmetic operators are processed in algebraic order:
- Parenthesis:
`( )` - Unary operators:
`+, -` - Multiplication, division, modulus:
`*, /, %` - Addition, subtraction:
`+, -`
- Parenthesis:
- Binary operators of same precedence are evaluated from left to right
- As in algebra, multiplication and division (including modulus) are performed before addition and subtraction
- To change the order of operation, we use parentheses
- For example:
is written as: `a + b / 2` is written as: `(a + b) / 2` - In the following examples, the fully parenthesized column shows the precedence explicitly
- Notice that we cannot use parenthesis to indicate multiplication, but must explicitly use the
`'*'` operator in C++
## Examples of Expressions
## 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 )`
We explore how we can use numbers and arithmetic in the following exercise. ## Check Yourself- The five arithmetic operators in C++ are ________.
`+, -, /, *, %` `+, -, \, *, %` `+, -, /, *, ^` `+, -, \, *, ^`
- The first operation performed in the following arithmetic expression is ________.
1 + 2 * 3 / 4 % 5 - If we wanted a different ordering of operations in the above example, we add ________ to the expression.
## 2.3.3: Mixed-Mode Expressions- Recall that different data types are stored in different forms
- An integer (
`int` ) is usually stored in 4 bytes - A floating-point number (
`double` )is usually stored in 8 bytes - The format the types are stored in is different as well
- An integer (
- 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`
## Check Yourself- The result of adding an integer with a double in the following expression is ________.
1 + 2.4 - In the above expression, C++ converts the integer
`1` to type ________. - The data type of the number returned by the following expression is ________.
3 + 4.5
## Exercise 2.3a: Calculator Basic (7m)Through the miracles of computer science, we will now convert your $500 computer into a $5 calculator! Along the way, we learn how to work with arithmetic using C++. ## Specifications- Go to the top of the class schedule page. Click on the link Sample Header. Copy the code into a text editor, update the header comment with your information and save it as
**arithmetic.cpp**, and then compile and run the starter program to make sure you're starting with correct code. - Within the curly braces of the
`main()` function, declare two`double` variables named`a` and`b` , and assign them a value of`5` and`2` respectively. For instance:double a = 5, 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; Notice that the last letter on `endl` is a lower-case "L", NOT a one. The output when you run the program should look like this:a + b = 7 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 = 7 a - b = 3 a * b = 10 a / b = 2.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 = 7 a - b = 3 a * b = 10 a / b = 2.5 a + b / 2 = 6 (a + b) / 2 = 3.5 Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra. For more information on the order of operations see section: 2.3.2: Arithmetic. 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 explore in the next section: - Truncation in integer division
- Modulus (%) operator
- Save your
`arithmetic.cpp` file as we will add to it in the following sections.
When completed, please help those around you. ## Discussion Questions- What is wrong with the following code?
cout << "a + b = a + b" << endl; - How should the above code be written?
## 2.3.4: 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, we 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- For a refresher on remainders see: Long Division with Remainders
- The modulus operator (%) can only be used with integer type operands and has an integer type result
- C++ allows a negative modulus result from a modulo operation
## Uses of Modulus and Division- We can use modular arithmetic for operations that roll over like clock arithmetic
- For example, if the time is 9:00 now, in 4 hours it is 1:00
int hours = 9; hours = (9 + 4) % 12; cout << hours << endl; - We can extend the same idea to work with weeks, minutes and seconds
- Modulus is also useful when working with different units like yards, feet and inches
- Another use of the modulus operator is to split the last digit off of an
`int` int num = 123; int lastDigit = num % 10; cout << lastDigit << endl; - We can get the first digit using integer division
int firstDigit = num / 100; - The middle digit(s) need a combination of integer division and modulus
int secondDigit = num / 10 % 10; - We can use modulus and integer division to translate integers to different bases as well
- For example, to convert from decimal to binary we use the same technique but divide by and take the remainder of 2 instead
## Program using Modulus to Split Digits (splitDigits.cpp)
## Check Yourself- In division between two integer numbers, the remainder is ________.
- rounded up
- rounded off
- averaged
- truncated
- To compute the integer remainder we use the operator ________ .
- What is the result of the following arithmetic operations?
- 9 / 4 (answer)
- 17 / 3 (answer)
- 14 / 2 (answer)
- 9 % 4 (answer)
- 17 % 3 (answer)
- 14 % 2 (answer)
## Exercise Continued: Using Integer Division (3m)In this part of the exercise we use integer division and modulus. **Integer Division**: Modify your`arithmetic.cpp` code from the last Exercise by changing the data type of the two variables from`double` to`int` , like this:**int**a = 5, 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). We have to watch out for this in C++ programming or we may get unexpected results in our 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; cout << "a / b % b = " << a / b % b << endl; cout << "a / (b * b) = " << a / (b * b) << endl; - Compile and run your program again with this added statement. Your program should now display the following output:
a + b = 7 a - b = 3 a * b = 10 a / b = 2 a + b / 2 = 6 (a + b) / 2 = 3 a % b = 1 a / b % b = 0 a / (b * b) = 1 - Save your
`arithmetic.cpp` file as we will add to it in the following sections.
When completed, be prepared to answer the following questions and then help those around you. ## Discussion Questions- What happens to a remainder in integer division?
- What is one use for the modulus operator?
- The last three operations produced the binary number
`101` . What is the decimal equivalent?
## 2.3.5: Mathematical Functions- 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 returns or produces a value ("output")
- To make use of mathematical functions we need to store or display the returned 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
#include <cmath> - Some of the functions are listed below
- Note that the
`pow()` function needs a floating-point type like`double` as the first argument
## Some Commonly Used Math Functions
## Some Commonly Used Nearest Integer Functions
- Nearest Integer Functions return integer numbers that are the closest to a floating point value
## 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); 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
## Check Yourself- C++ mathematical functions take an ________ and return a value.
- The name of the library that contains many common mathematical functions is ________
- Enter an expression to calculate the square root of the number
`49` . - To
*round up*a number, call the mathematical function ________. - Use a ________ to save the value returned from a mathematical function.
## Exercise 2.3b: Calculator Deluxe (3m)In this part of the exercise we use mathematical functions to create a deluxe calculator. ## Specifications- Start with your
`arithmetic.cpp` code from the last Exercise 2.3a. - 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 = 7 a - b = 3 a * b = 10 a / b = 2 a + b / 2 = 6 (a + b) / 2 = 3 a % b = 1 a / b % b = 0 a / (b * b) = 1 sqrt(a + b) = 2.64575 - Submit your arithmetic.cpp that displays all eight (8) calculator operations to Canvas Ex 2.3b.
When completed, please help those around you. ## Completed Code
int a = 5; int b = 2; cout << "a + b = " << a + b << endl; cout << "a - b = " << a - b << endl; cout << "a * b = " << a * b << endl; cout << "a / b = " << a / b << endl; cout << "a + b / 2 = " << a + b / 2 << endl; cout << "(a + b) / 2 = " << (a + b) / 2 << endl; cout << "a % b = " << a % b << endl; cout << "a / b % b = " << a / b % b << endl; cout << "a / (b * b) = " << a / (b * b) << endl; cout << "sqrt(a + b) = " << sqrt(a + b) << endl; return 0;
## Discussion Questions- How natural does arithmetic seem in C++ compared to what you normally use?
- A mathematical function has an input and an output. What is the input and output of the C++
`sqrt()` function? - What is the value of 2.64575 squared?
## 2.3.6: Summary- C++ uses the following operators for arithmetic:
`+` for addition`-` for subtraction`*` for multiplication`/` for division`%` for modulus (remainder)
- The dash is also used for negation (minus sign)
- We write arithmetic expressions using combinations of numbers, variables and operators, like:
double area = 0.0, radius = 4.3; area = 2.44159 * radius * radius; - As in algebra, multiplication and division are performed before addition and subtraction
- To change the order of operation, we use parenthesis
- Recall that the results of integer division are truncated
7 / 2 // 3 - We must use modulus operator (
`%` ) to get the remainder value7 % 2 // 1 (remainder) - For more complex operations we use mathematical functions from libraries such as cmath
cout << sqrt(3.0 * 3) << endl; - C++ processes arithmetic expressions in the same order (precedence) as algebra:
- Parenthesis:
`( )` - Function calls
- Unary operators:
`+, -` - Multiplication, division, modulus:
`*, /, %` - Addition, subtraction:
`+, -`
- Parenthesis:
- Since parenthesis are processed first, we use parenthesis to change the order of operations
## Self ReflectionAnswer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material. - How can you tell the difference between an integer and a floating-point number? (2.3.1)
- What are the five operators C++ provides for arithmetic? (2.3.2)
- What is the first operation performed in the expression:
`1 + 2 * 3 / 4 % 5` ? (2.3.2) - What is the data type returned by the following expression? (2.3.3)
3 + 4.5 - What happens to the remainder during integer division? (2.3.4)
- What operator can you use to compute the integer remainder? (2.3.4)
- What is the result of the following arithmetic expressions? (2.3.4)
5 / 4 5 % 4 - What is a function? (2.3.5)
- What code do you write to calculate the square root of the number
`49` ? (2.3.5)
## 2.4: Errors and Debugging
## 2.4.1: Errors and Error Messages- As we develop programs, we make errors
- These errors are known euphemistically as "bugs" (See the first computer bug)
- Grace Hopper, an early computer pioneer, popularized the term debugging
- Often the error is because we left out a character or misspelled a word
- In programming, one small mistake means the program does not work
- The following are some types of errors we may encounter
## Syntax Errors- One type of error is the syntax error or compile-time error
- This means our source code violates the language rules
- The good news: our compiler finds the error
- Some examples:
cot << "Hello, World!\n"; cout << "Hello, World!\" - Common syntax errors include
- Missing semicolon (;)
- Misspelled letters in commands
- Missing curly braces
- Missing parenthesis
- Comments without comment symbols
## Logic Errors- Another type of error is the logic error:
- Logic errors are mistakes in the program's algorithm
- Our program does not do what it is supposed to do
- For example:
cout << "Hell, World\n"; - The compiler does not find these types of errors for us
- Instead, we must run our program and look for errors in how it operates
- Running a program and looking for errors is known as testing
## Run-time Errors- A third type of error that we may encounter is the run-time error
int x = 0; cout << 1 / x; - Run-time errors cause our program to exit with an abnormal error ("crash")
## Errors Versus Warnings- If we violate a syntax rule, the compiler gives us an error message
- However, sometimes the compiler will give us a warning message instead
- For example:
erroneous.cpp:10:1: warning: "/*" within comment - This indicates that our code is technically correct
- However, the code is unusual enough that it may be a mistake or is otherwise undesirable
- Thus, you lose points for warning messages in your programming assignments
## Check Yourself- True or false: one of the goals of testing is to find and correct errors.
- The program that tests if your program has a syntax error is known as a(n) ________.
- True or false: the hardest error to find is a syntax error.
- To test for logic or runtime errors, you must ________ your program.
- True or false: warnings are technically not errors so it is safe to ignore them.
## 2.4.2: Preventing Bugs- It may sound obvious, but the best way to debug is to not write bugs into our code
- Being careful with our code and design can take less time than tracking down a strange bug
- The following are some bug-prevention techniques that will help us limit the number of bugs we produce
## Start With a Plan- Have a plan before you start writting code
- Develop a list of steps you think are required (an algorithm)
- Once you have an algorithm then translate the steps to C++
## Compile After Writing a Statement- The worst way to develop a program is write all the code before compiling
- Trying to find all the errors becomes more difficult as the program grows larger
- Instead, every time you write a line (or so) of code, compile your program
- This way you know the location of the syntax errors
## Review Before Testing- Do not "compile, run, and pray"
- When we write a section of code, first check the logic of the algorithm
- Work through the code mentally to check if it will work
- If we already have an algorithm developed, we check the code conforms
- By preventing problems, we will spend much less time fixing bugs
## Write Readable Code- During the course we will discuss common style techniques used by professional programmers
- By following these techniques, our code looks more professional
- Also, following these techniques reduces the number of errors we produce
- For instance, we discussed indenting code inside of curly braces
- By indenting properly, our code is more readable by both ourselves and others
- By formatting our code consistently, we can spot problems more easily and reduce errors
## Check YourselfAnswer these questions and then verify your answers with your deskmate. - True or false: the best way to debug is not to write bugs in the first place.
- We should always compile after writing every line or two of code because ________.
- the compiler will tell you about syntax errors
- we know the location of any errors reported
- it is easier to prevent problems than correct them
- of all of these
- After writing every section of code, always double check the conformance to the algorithm or ________.
- logic
- scope
- spelling
- syntax
- True or false: following a professional programming style makes it easier to see and prevent bugs.
## 2.4.3: Debugging Syntax Errors- Despite our best efforts we still create bugs in our code
- To debug our programs we have to read the error messages
- As we read them we need to extract the important information
- For example, this error message tells us several important things:
fiddle.cpp: In function `int main()': fiddle.cpp:6: error: parse error before `return'
- The name of the file
**fiddle.cpp**: In function `int main()': - The function where the error occurs
fiddle.cpp: In function ` **int main()**': - The line number of the error
fiddle.cpp: **6**: error: parse error before `return' - The error description
fiddle.cpp:6: error: **parse error before `return'**
- The most immediately useful information is the line number
- This tells us the approximate location of the error in the source code
- In general, we should look at the first error or warning and ignore the rest
- Often the first error or warning causes all the rest of the errors and warnings
- For step-by-step instructions on debugging syntax errors, see: How To Debug Syntax Errors
## Check Yourself- In the following error message, the most immediately useful information is the ________.
fiddle.cpp: In function `int main()': fiddle.cpp:6: error: parse error before `return' - error message
- file name
- function name
- line number
- True or false: generally, we should recompile after correcting the first error because the first problem may have caused all the error messages and compiling is fast.
## More Information## Exercise 2.4: DebuggingIn this exercise we practice finding and fixing errors with a partner. ## SpecificationsThe following program was written by a person in a hurry. During the writing process a large number of errors were made. ## Erroneous Program
## Part A: Peer Review## Find a partner for this exercise and create a text file named |

Schedule >