2. Variables and expressions

Review Topics

General Information

Housekeeping

  • Make sure you follow along with this page linked in Canvas
  • Please keep your microphone off unless you are asking a question
  • Please turn on camera if you can (optional)
  • Use chat if you would like to comment or ask questions

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few other items:

  • Remember to vote by 9/14 like your freedom and rights depend on it! (register or Same Day Voter Registration)
  • Vacinations required to visit campus
  • Must complete all Module 0 and 1 assignments, and Module 2 PAs, or you may be dropped from the course
  • Can still update solo quizzes and other assignments if less than full score until 9/3
  • ZyBook required for course:
    • Free to sign up and read first chapter
    • Email Zybook support if you do not have immediate funds--should give two more weeks
    • Email me if purchase is a financial hardship
  • Remember that the exercises from this page are due Sunday at 9:00pm.
  • Grace period--assignments due before 9/3 can completed be until 9/3 at 9:00pm (except Team quizzes)
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access
  • Student TechHelp job openings: flyer
  • Extra credit bonus points for the first student to report a problem

Homework Help

2.1: Readiness Assessment Quizzes

  • Reading and participation activities are due before the first class meeting of the week
  • Quizzes assess the comprehension of the reading and participation activities

Quiz Part 1: Individual Readiness Assessment

  • Complete this quiz solo to assess your reading comprehension and readiness
  • Must take this quiz before the class meeting to ensure you are ready for the team quiz
  • Quiz is open book and notes but timed
  • Highest score is counted so take the quiz multiple times

Quiz Part 2: Team Readiness Assessment (15m)

  • Must attend the class meeting to take this quiz
  • Login to Canvas
  • Will move to breakout rooms with your team
  • Make sure you have the access code for the exam
  • Submit the quiz individually during the first two weeks but work on it as a group
  • Openly discuss what you believe to be the best answers for the questions
  • Decide how to agree on the answers
    • Strive to reach a consensus on quiz answers
    • If no consensus, work it out as you and others in your group see fit
  • Turn in the quiz individually as agreed upon by the group
  • Each group member will receive the same score
  • Return to the main meeting room when finished

Quiz Appeals

  • After completing the team quiz, team members may appeal an answer
  • Appeals can be based on two criteria:
    1. Question is factually wrong

      Appeal must included citations to sources of information that document or support an alternative answer. Team may access reference materials during the appeal.

    2. Question is confusing based on it's wording

      Appeal must include an appropriate rewrite of questions or answers that you interpret as ambiguous or confusing.

  • Work with teammates to develop and write any appeals
  • Team has up to 24 hours after the quiz to email appeal to instructor
  • If appeal is granted, only the teams that submitted appeal gets credit

2.2: Reviewing computers and programming

In this section we review how computers are organized and how programs make use of computers.

2.2.1: Programming languages and C++

Recall how a computer is organized:

computer diagram

Processor (CPU)

Processor (CPU)

  • The heart of a computer is the Central Processing Unit (CPU or processor)
  • A processor executes machine instructions, which are extremely primitive operations like:
    1. Move memory location 40000 into register eax
    2. Subtract the value 100
    3. If the result is positive, start processing at location 11280
  • These instructions are encoded as numbers such as:
    161 40000 45 100 127 11280
  • While the computer only understands binary, we use decimal numbers for convenience

Assemblers

  • Each processor has its own set of machine instructions (commands)
  • Looking up numeric codes for instructions like these is tedious and error prone
  • To make programming easier, computer scientists first developed a program called an assembler
  • An assembler allows a programmer to assign short names for the machine codes like:
    movw r30, r24     (copy register word - word is 4 bytes)
    subi r30, 0x12    (subtract immediate)
    breq .+8          (branch if equal)
    
  • The assembler translates the names into the correct machine codes
  • While easier for humans to use, assemblers still have two problems:
    1. We still have to enter a great many primitive instructions to create a program
    2. The instructions change from one processor to another

Higher-level Languages

  • To make programming easier, computer scientists developed high level languages
  • Higher-level languages like C++ and Java let us write more readable instructions like:
    if (interestRate > 100) {
        cout << "Interest rate error";
    }
    
  • Programmers call these instructions source code
  • To translate these high-level instructions to machine instructions we use a compiler

    compiler: a program that translates source code into machine instructions

  • Another advantage of higher-level languages is we can move programs to another processor more easily
  • Moving programs to another processor requires someone to write a compiler
  • After the new compiler is available, we can recompile our program with (hopefully) no changes
  • There are thousands of higher-level languages
  • The one we use in this course is C++

Early History of C++

  • C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s
    • 1973 - UNIX kernel rewritten in C
    • 1978 - K&R C specified based on the book The C Programming Language
    • 1989 - ANSI C standard released
  • C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s
    • 1979 - Stroustrup begins work on "C with Classes"
    • 1982 - Name changed to C++
    • 1983 - First used by AT&T
    • 1985 - First commercial use
    • 1988 - ANSI C++ standard released
    • 1998 - ANSI-ISO standard released as ISO/IEC 14882
    • 2003 - Amended 1998 standard (ISO/IEC 14882:2011)
    • 2011 - Several additions to the core language (ISO/IEC 14882:2011)
    • Standard updated every three years...
    • 2020 - Most recent version (ISO/IEC 14882:2020)

Check Yourself

  1. True or false: computers can directly carry out C++ source code instructions.
  2. True or false: an assembler translates high-level language programs to a set of computer instructions.
  3. To translate source code to machine code we use a ________.
  4. For a high-level language like C++, which of the following statements are true?
    1. Easier to program than machine code
    2. Easier to program than assembler code
    3. Easier for a human to read and understand
    4. Easier to move from one type of processor to another
  5. True or false: the ANSI standard for C++ was released after the ANSI standard for C.

More information

2.2.2: Example Program

  • Here is an example program like we looked at before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    /**
       CS-11 Prints a message to the screen.
       @author Ed Parrish
       @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
       cout << "Hello, World!\n";
       return 0;
    } // end of main function
    

Brief Explanation by Line Number

  • Lines 1-5: comments -- notes to programmers about the program
  • Line 6: adds a library (pre-written code) to our program
  • Line 7: all the standard libraries use the std namespace
  • Line 8: a blank line to separate groups of statements
  • Line 9: the main() function where all C++ programs start
  • Line 10-11: programming statements that give instructions to the computer
  • Line 12: the end of the main() function followed by another comment

2.2.3: Comments

  • Comments are ... comments -- notes to people reading the code
  • A compiler ignores comments
  • Use comments to document blocks of code and to describe unusual code
  • One form of comments starts with // and lasts to end of the line
    // this is a C++ style comment
  • Another style of comment affects a section of code: /* ... */
  • This form can span multiple lines:
    /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line.
    */
    
    or just a portion of one line
    x = /* 41 + */ 1 ;
    

Programming Style: Block Comments

  • Block comments are the main way to document a section of code
  • We use block comments like the following at the start of a program file:
    /**
       CS-11 Prints a message to the screen.
       @author Ed Parrish
       @version 1.0 8/30/05
     */
    
  • The grading of most programming projects includes checking the comments of our code
  • Put a comment like this at the top of the source code file for all labs (like ZyLabs)
  • However, there is usually no need to put comments in lesson exercises, PAs or CAs

Check Yourself

  1. True or false: comments are notes to the compiler.
  2. Of the following, the symbols that indicate a single line of commentary will follow is ________.
    1. /*
    2. /**
    3. //
    4. */
  3. To make C++ code more explanatory for other people ________.
    1. use more English statements in the code.
    2. add comments to code
    3. avoid usage of complex calculations in code
    4. always enclose code statements in curly braces
  4. Of the following, the type of comments to use at the top of each programming project file is ________.
    1. /*...*/
    2. /**...*/
    3. //...
    4. #...
  5. True or false: comments are generally required in lesson exercises.

2.2.4: Statements and whitespace

  • Statements are commands we give a computer in a programming language
  • A statement is similar to a sentence in English
  • Most statements end in a semicolon (;)

Example Statement: cout

  • One of the many statements of C++ is: cout << something;
  • This statement is one way to send output to a console
  • For example, the statement:
    cout << "Hello, World!";
    
  • Sends "Hello, World!" to the console like this:
    Hello, World!
    

Programming Style: Statements and Line Length

  • Each statement appears on its own line
  • Do not make your lines longer than 80 characters so code is easier to read
  • Longer lines can cause problems in many terminal windows, text editors and other programming tools
  • Split longer lines at operators like: <<
    cout << "This is a really long line of text that can be continued "
         << "on the next line." << endl;
    

Preprocessor Directives

  • Some commands we place in our source code start with a # sign
    #include <iostream>
    
  • Technically, this command is known as a preprocessor directive
  • A preprocessor directive is a command to the compiler rather than a command to the computer
#include <iostream>
using namespace std;

int main() {
   cout << "Hello, World!\n";
   return 0;
}

Whitespace

  • Whitespace: blank lines, spaces, and tabs
  • The compiler ignores extra white space
  • This lets us add extra whitespace to our code, making it easier to read

Programming Style: Whitespace

  • Most items are separated by one space (and not less or more)
    cout << "Hello, World!\n";
  • No space precedes an ending semicolon
  • A blank line can separate conceptually distinct groups of statements
  • Related statements usually have no blank lines between them

Check Yourself

  1. Statements usually end in a ________.
  2. To make the code easier to read, always limit line lengths to ________ characters.
  3. True or false: the compiler ignores extra whitespace.

2.2.5: The main() function and blocks

  • C++ programs are structured into subprograms called functions

    Function - a named block of code that executes a series of statements to perform a task

  • Every C++ program has at least one function, main, defined like this:
    int main() {
       // program statements go here
       return 0;
    }
    
  • Programs begin executing at the first line of the main() function
  • The int means main returns a value of type int (more on this later)
  • For now, mimic the first line of main and end with:
    return 0;

Sequence

  • Within a function, code runs from top to bottom in a continuous sequence
  • Example code sequence:
    cout << "Hello World!\n";
    cout << "Goodbye World!\n";
    return 0;
    
  • For a program to run correctly, we must place statements in the correct order

Blocks and Braces

  • C++ is known as a block-structured language
  • A block in C++ is a section of code grouped together with { }
  • This means that most source code is grouped within pairs of matching { }
  • Left brace { begins every block
  • Right brace } ends every block
  • All functions have associated blocks
  • However, as we will see later in the course, we group statements into blocks in other places as well

Programming Style: Indentation Inside Braces

  • Always indent statements by 3 spaces inside braces to make code easier to read
  • After an opening curly brace "{", start indenting
  • When reaching the closing brace "}", remove the level of indentation
#include <iostream>
using namespace std;

int main() { // start indenting after opening {
   cout << "Hello, World!\n";
   return 0;
} // stop indenting after the closing }

Check Yourself

  1. True or false: every C++ program has at least one function.
  2. A C++ function is ________
    1. A mapping of a domain value to a codomain value
    2. A named block of code that executes a series of statements
    3. A named block of code that returns a value for a given argument
    4. Any procedure that returns a value
  3. True or false: every C++ program has a main() function.
  4. Every C++ program starts executing ________.
    1. at the top of the file
    2. at the start of the main function
    3. immediately after the program compiles
    4. when the program is finished
  5. True or false: the default behavior for program statements within a function is to execute sequentially.
  6. A block is a section of ________ grouped together with curly braces.
  7. True or false: always indent within curly braces.

Exercise 2.2: Elementary C++ (10m)

In this exercise we review the basic elements of a C++ program.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications Part A: Experimentation

  1. Start Repl.it and copy the following code into the code editor.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    /**
       CS-11 Prints a message to the screen.
       @author Ed Parrish
       @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
       cout << "Hello, World!\n";
       return 0;
    } // end of main function
    
  2. Run the code and verify you get the message, "Hello, World!"
    Hello, World!
    
  3. Try changing the message to personally greet you with your own name, like the following:
    Hello, Ed Parrish!
    
  4. The code that starts with /** 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 teammate for help as needed.

  5. Look at the following line of the code:
    } // end of main function
    The 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 teammate for help as needed.

  6. Remove the directive 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.

  7. Restore the directive using namespace std; back into your program and verify that it compiles.

    If you have problems, ask a teammate for help as needed.

  8. Once satisfied with your code, copy it into a text editor, save the file as "hellome.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished with Part A, move on to Part B.

Specifications Part B: Reflection

  1. Create a second text file named "syntax.txt", discuss the answers with your team, and record your answers to the following questions:
    1. Does a comment change the way that a program compiles or runs?
    2. What error message does the compiler report when you leave out the following command?
      using namespace std;
  2. Submit both your hellome.cpp and syntax.txt files to Canvas with the rest of the exercise files for the week.

When finished, please help your teammates and then return to the main class meeting.

2.3: Reviewing Variables

Memory organized by bytes

  • Recall how a computer is organized with an area of memory
  • 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

2.3.1: Storing data in variables

  • A key part of a computer 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

Variables are a location in the computers memory

Defining variables

  • Here is an example C++ variable definition:
    int num1;
    
  • When we define a variable we tell the computer to set aside space to store data in its memory
  • Notice that a variable definition 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

  • A variable name is a sequence of letters, digits, underscores ( _ ) and currency symbols like a $
  • However, the name must start with either a letter, underscore character ("_") or currency symbol
    • Cannot start with a number
    • A currency symbol is allowed but do not use
  • Also, a variable name cannot be one of the C++ reserved words (keywords)
    • For a list of reserved words, see: C/C++ Keywords
    • Keywords have a predefined meaning in the C++ language
  • No spaces in a variable name
    • A space is NOT a letter, digit, underscore character or currency symbol
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember
    • Well-chosen identifiers make it easier for other programmers (like the instructor) to understand your program
    • For example, the following is syntactically correct:
      a = b * c;
    • However, it hides the intent or meaning
    • Contrast this with:
      weeklyPay = hoursWorked * payRate;
    • This tells other programmers the intent and meaning of the code
  • Notice that variable names are camelCase, starting with a lowercase letter with new words in uppercase

2.3.2: 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

Type Bytes Use
int 4 integers (whole numbers) like -1, 0 and 123
double 8 double-precision floating-point numbers like -1.23 and 3.14159

2.3.3: Assigning values

  • After we declare a variable, we may store a value in the variable
  • One way to store values is with an assignment operator, which is the "equals sign" (=)
  • We assign a value to the variable with an assignment statement in this form:
    variable = expression;
  • Where:
    • variable: the name of the variables
    • expression: the symbols that express the data to store
  • An assignment statement stores the value of expression (right side) in the variable (left side)
    • Switching sides is a common error
  • An expression is a group of operators, numbers and variables that compute a value
  • An assignment statement is like a simple equation where an expression is assigned to a variable
  • Examples:
    int num1;       // variable definition
    num1 = 45;      // assignment
    int num2 = 12;  // definition + assignment
    int total = num1 + num2;  // more complex expression
    
  • Notice that we may combine variable definition with assignment
  • A common error is to forget to assign a value to a variable!!!
  • Avoid this error by assigning a value whenever declaring a variable

Variables by Analogy

Empty box labeled a

  • Variables are like boxes made of computer memory (images source: David Goodger)
  • A computer memory location can hold one value at a time, thus our box can hold only one value
  • We put names on boxes to tell one box from another, like "a":
  • This is like declaring the 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 values in a box

    value 1 in box a

  • For example, we assign the variable "a" the value 1
    a = 1;
    
  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we output it with code like:
    cout << a << endl;
    
  • If we change the value of a variable, we are putting a new value in the same box, like:

    value 2 in box a

    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;
    

    value 2 in box bvalue 2 in box a

  • We now have two different boxes that have independent values

Exercise 2.3: Variable Assignment Tracing (25m)

Understanding variables and assignment is critical to being able to program but can be confusing at first. Get over this hurdle and programming will be far easier.

For this exercise we break into teams. Within the team, work with each other to complete a series of exercises where you step through short fragments of code. This is an important activity to reinforce your understanding of variables. The instructor will step through the first exercise with you.

Suggestion: for each exercise, try working through the boxes for the problem on your own and then compare answers with the rest of the team. Correct any errors and then repeat for the remaining problems.

Specifications

  1. Start a text editor and create a file named variables.txt
  2. Open the Variable Assignment Tracing Exercises page.
  3. Click the first problem and follow the steps, filling in the boxes to get the final answers.
  4. After completing a problem and before continuing to the next, compare your answers with other team members.

    Discuss and resolve and discrepancies between answers.

  5. After verifying your answer, record the problem number and final values of all variables in your variables.txt file.

    As an example for problem 1:

    1. Final value of x is 7. Final value of y is 7.
    
  6. Repeat this process for the remaining exercise problems.
  7. After finishing all the exercise problems, answer the Check Understanding questions and record the question number and answer on your paper.

    As an example for question 10a:

    10a. false
    

When finished, please help your team members and then return to the class meeting.

2.4: Math expressions

  • 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

2.4.1: Numerical types

  • Remember that C++ has two general types of numbers: integers and floating-point
  • We identify which type of number we use with the data type

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 value but is not a literal integer
    int num1 = 3;
    
  • Literal numbers are constant and do not change while a program executes
  • The compiler usually stores integers 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
  • The compiler usually stores floating-point numbers in eight (8) bytes of computer memory

Assigning Initial Values to Variables

  • As programmers we must decide whether or not to initialize variables when declared:
    // Not initialized when declared and have unknown values
    int sum;
    double amount;
    
    // Initialized when declared with assigned values
    int sum = 0;
    double amount = 42 * 2;
    
  • Good programming practice: initialize variables when declared

2.4.2: Constants and Magic Numbers

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Constant variable seems oxymoronic, but is actually quite useful
  • To declare a constant, we use the keyword: const
    const int MY_CONST = 1;
    
  • We must assign a value when the constant is declared
  • If we tried to assign a value in a later statement, we get a compile-time error
  • Notice that the name is all uppercase letters with an underscore separator
  • The all uppercase convention identifies the variables as constant
  • This is a common coding convention that professional programmers follow

Magic Numbers

  • Imagine that we are hired to modify a payroll program
  • We come across the following section of code:
    int hours = 45;
    double pay;
    pay = hours * 10 + (hours / 40)
          * (hours - 40) * 10 * 0.5;
    
  • The numbers are important to the program, but what do they mean?
  • Numbers like these are called "magic numbers"
  • They are magic because their value is unexplained but necessary
    • Often, no one knows what they mean after 3 months, including the author
  • We can often deduce the meaning of numbers after reading the code carefully, which is time consuming
  • A much better coding style is to use named constants rather than literal numbers
  • For example:
    const double WAGE = 10;
    const double OVERTIME_BONUS = 0.5;
    const int HOURS_PER_WEEK = 40;
    double pay;
    pay = hours * WAGE + (hours / HOURS_PER_WEEK)
          * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_BONUS;
    
  • Now it is much easier to understand the code and see any problems or limitations
  • Another reason to use named constants is that it is easier to change the code when the number changes
  • In the above example, we can easily change WAGE without making errors in other parts of our code

Programming Style: Constant Variables and Magic Numbers

  • Since the meaning of literal ("magic") numbers is hard to remember, we declare constants instead:
    const int FEET_PER_YARD = 3;
    const double PI = 3.14159265358979323846;
    const double WAGE = 7.5;
    const double OVERTIME_ADDER = 0.5;
    const int HOURS_PER_WEEK = 40;
    
  • Note that the name is all uppercase letters with an underscore word-separator
  • This is a common coding convention that you must follow for your constants
  • From widespread use and for practical reasons, -1, 0, 1, and 2 are usually acceptable magic numbers

More Information

Check Yourself

  1. A numeric literal that is not assigned to a constant is known as a ________ number.
  2. Rather than use a "magic" number, instead always use a named ________.
  3. Write the code to declare a constant double named BIG_NUM and assign it a value of 100,000.

    answer

Exercise 2.4a: Declaring constants (10m)

In this exercises we declare constant variables.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Declare constant variables and assign them the following numerical values:
    1. The count of the number of people in this meeting (see participants)
    2. Michael Jordan's jersey number (23)
    3. The price of a new toy ($15.42)
    4. The price of a new cell phone ($349.99)
    5. The value of Pi (3.14159265359)
  3. Compile your code to make sure you added the constants correctly.
  4. Write an output statement for each constant followed by a newline.
  5. Compile and run your code to make sure you added the code correctly.

    When you run the program, the output should look like:

    42
    23
    15.42
    349.99
    3.14159
    
  6. Once satisfied with your code, copy it into a text editor, save the file as "myconst.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

2.4.3: 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:
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • 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:

    a + b / 2 is written as: a + b / 2

    (a + b) / 2 is written as: (a + b) / 2

  • Notice that we cannot use parenthesis to indicate multiplication, but must explicitly use the '*' operator in C++

Examples of Expressions

Algebra Expression C++ Expression
2(10 + 5) 2 * (10 + 5)
1

12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3)
10 - 7

3.2 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6)
2 · 42 2 * 4 * 4

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 )

Program coins.cpp to Sum Coins

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main() {
    int pennies = 8;
    int nickels = 5;
    int dimes = 4;
    int quarters = 3;

    double total = pennies * 0.01 + nickels * .05
        + dimes * 0.10 + quarters * 0.25;

    cout << "Total value = " << total << "\n";

    return 0;
}

Check Yourself

  1. The five arithmetic operators in C++ are ________.
    1. +, -, /, *, %
    2. +, -, \, *, %
    3. +, -, /, *, ^
    4. +, -, \, *, ^
  2. The first operation performed in the following arithmetic expression is ________.
    1 + 2 * 3 / 4 % 5
    
  3. If we wanted a different ordering of operations in the above example, we add ________ to the expression.

Exercise 2.4b: Calculator Basic (15m)

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++.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it, update the code in the text editor, and then compile and run the starter program to make sure you typed it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Type your code here
    }
    
  2. 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;
    
  3. 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. Verify the output of the program looks like this:

    a + b = 7
    

    If you do not see this output, please type a chat message asking for help.

  4. 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
    
  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;
    
  6. 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.4.3: Arithmetic.

    As you can see, arithmetic in C++ works much like you would expect.

  7. Once satisfied with your code, copy your code into a text editor, save the file as "arithmetic.cpp", and to submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

2.4.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;
    

    clock faces

  • 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
  • For example, 49 inches is 1 yard, 1 foot and 1 inch which is calculated like:
    int lengthInches = 49;
    int yards = lengthInches / 36;
    int remainder = lengthInches % 36;
    int feet = remainder / 12;
    int inches = lengthInches % 12;
    cout << yards << " yards, "
         << feet << " feet and "
         << inches << " inches\n";
    
  • 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;
    

Program using Division and Modulus to "Split" Digits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main( ) {
    int num = 1234;
    cout << num << ": ";
    int digit1 = num % 10; // rightmost digit
    int digit2 = num / 10 % 10;
    int digit3 = num / 100 % 10;
    int digit4 = num / 1000 % 10;
    cout << digit1 << " " << digit2 << " "
         << digit3  << " " << digit4 << endl;

    return 0;
}
  • We can use modulus and integer division to translate integers to different bases as well
  • For example, to convert from decimal to binary we divide by 2 and take the remainder of 2 instead of 10

Program Changing Decimal to Binary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
    int decimalNum = 6, newNum = 0; //what is 6 in binary?
    int firstBit = 0, secondBit = 0, thirdBit = 0;
    firstBit = decimalNum % 2; //rightmost bit
    newNum = decimalNum / 2;
    secondBit = newNum % 2;
    newNum = newNum / 2;
    thirdBit = newNum % 2;
    cout << decimalNum << " in binary is "
         << thirdBit << secondBit << firstBit << endl;
    return 0;
}

Check Yourself

  1. In division between two integer numbers, the remainder is ________.
    1. rounded up
    2. rounded off
    3. averaged
    4. truncated
  2. Of the following, the expression that returns an integer value is ________.
    1. 22.0 / 7
    2. 22 / 7.0
    3. 22.0 / 7.0
    4. 22 / 7
  3. To compute the integer remainder we use the operator ________ .
  4. What is the result of the following arithmetic operations?
    1. 9 / 4   (answer)
    2. 17 / 3 (answer)
    3. 14 / 2 (answer)
    4. 9 % 4   (answer)
    5. 17 % 3 (answer)
    6. 14 % 2 (answer)

Image
Source: Wikipedia

2.4.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

Name Description Example Result
abs absolute value abs(-3.9)
abs(3.9)
3.9
3.9
exp exponent of e (ex) exp(1.0) 2.71828
pow powers (xy) pow(2.0, 3) 8
sqrt square root sqrt(4.0) 2
sin sine sin(0.0) 0
cos cosine cos(0.0) 1

Some Commonly Used Nearest Integer Functions

Name Description Example Result
ceil ceiling: round up ceil(3.456)
ceil(3.543)
4
4
floor floor: round down floor(3.456)
floor(3.543)
3
3
round rounding: round off round(3.456)
round(3.543)
3
4
  • Nearest Integer Functions return floating point numbers that are the closest to an integer 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, the expression uses the returned value
  • 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

  1. C++ mathematical functions take an ________ and return a value.
  2. The name of the library that contains many common mathematical functions is ________
  3. answer

  4. To round up a number, call the mathematical function ________.
  5. Use a ________ to save the value returned from a mathematical function.

Exercise 2.4c: Calculator Deluxe (10m)

In this exercise we use integer division, modulus, and mathematical functions to create a deluxe calculator.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. In Repl.it, start with your arithmetic.cpp code from the last Exercise.
  2. 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;
    
  3. 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.

  4. 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 statements after the other cout statements:
    cout << "a % b = " << a % b << endl;
    cout << "a / b % b = " << a / b % b << endl;
    cout << "a / (b * b) = " << a / (b * b) << endl;
    
  5. 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
    
  6. 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.
  7. Add the following statement to your program:
    cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
    
  8. Your 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;
    
  9. 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
    
  10. Once satisfied with your code, copy your code into a text editor, save the file as "calculator.cpp", and to submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

Last Updated: September 25 2021 @20:21:44