Home‎ > ‎CS 11M‎ > ‎

Mathematical Operations

Questions, Answers and Review

  • Questions from last class?
  • Questions about homework?

Numbers and Arithmetic

Computations Using Numbers and Arithmetic

  • Many problems can be solved using mathematical formulas and numbers
  • For example, if we want to calculate voltage using Ohm's law, we use the formula:
    voltage = current (in amps) * resistance (in ohms);
    
  • An algorithm we might follow to calculate the voltage is:
    1. Get the current in amps
    2. Get the resistance in ohms
    3. Calculate voltage using the formula
    4. Display the answer
  • To implement this formula in code, we will need to use numbers and arithmetic

Types of Numbers

  • C++ has two general types of numbers: integers and floating-point
  • An integer 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
  • The other type of number is a floating-point number
  • A floating-point number is any signed or unsigned number with a decimal point
  • 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 -- how?
  • In C++, both integers and floating-point numbers cannot have any commas or special symbols
  • The following program implements an algorithm for calculating voltage
  • Make sure to set the Serial Monitor to "No Line Ending" when running the example below

Voltage Computation

#include <ArduinoSTL.h>

using namespace std;

void setup() {
  Serial.begin(9600);
  cout << "Enter the current in amps" << endl;
  double amps = 0, ohms = 0;
  cin >> amps;
  
  cout << "Enter the resistance in ohms" << endl;
  cin >> ohms;
  double volts = amps * ohms;
  cout << "The voltage is " << volts << endl;
}

void loop() {
  // no code here
}

Check Yourself

  1. The two types of numbers in C/C++ are ________ and ________.
  2. Of the following literal numbers, the single integer is ________.
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  3. For the following code, the literal number is ________
    Serial.begin(9600);
    

Arithmetic

  • C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after integer division)
  • The first four operators should be familiar and we will discuss modulus (%) today
  • 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

Notes About Arithmetic

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

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 )

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.

Mixed-Mode Expressions

  • Different data types are stored in different sizes on the Arduino, like:
    • An int is stored in 2 bytes
    • A float or double is stored in 4 bytes
  • The numbers are stored in different binary formats as well:
  • The computer needs both operands in the same format before it can perform arithmetic
  • 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/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

  1. The result of adding an integer with a double in the following expression is ________.
    1 + 2.3
  2. In the above expression, C++ converts the integer 1 to type ________.
  3. The data type of the number returned by the following expression is ________.
    3 + 4.5

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
  • For a refresher on remainders see: Long Division with Remainders

Program Testing for Even or Odd Numbers

#include <ArduinoSTL.h>

using namespace std;

void setup() {
  Serial.begin(9600);
  cout << "Enter an integer number" << endl;
}

void loop() {
  int testNum;
  cin >> testNum;
  int quotient = testNum / 2;
  int remainder = testNum % 2; //pronounced testNum "mod" two
    cout << testNum << " / 2 = " << quotient << endl;
    
    cout << "The remainder is " << remainder;

    if (0 == remainder) {
      cout << " (even)" << endl;
    } else {
      cout << " (odd)" << endl;
    }
}

Check Yourself

  1. In division between two integer numbers, the remainder is ________.
    1. rounded up
    2. rounded down
    3. averaged
    4. truncated
  2. To compute the integer remainder we use the operator ________ .
  3. What is the result of the following arithmetic operations?
    1. 9 / 4
    2. 17 / 3
    3. 14 / 2
    4. 9 % 4
    5. 17 % 3
    6. 14 % 2

Mathematical Functions

  • Operators provide only the simplest mathematical operations
  • For more complex operations, we use mathematical functions
  • A C/C++ function is like a mathematical function that takes an argument ("input") and produces ("returns") a value
  • For example:
    cout << sqrt(9.0);
  • In the above example, the input is 9.0 and the sqrt() function returns the square root of the argument
  • The Arduino IDE has built in Math and Trigonometry functions documented in the Language Reference
  • Some of the commonly used functions are listed below

Some Commonly Used Math Functions

Name Description Example Result
abs (value) Absolute value of a number abs(-3.9)
abs(3.9)
3.90
3.90
max (x, y) Maximum of two numbers max(1, 2.2) 2.20
min (x, y) Minimum of two numbers min(1, 2.2) 1.00
pow(base, exp) Number raised to a power (xy) pow (2.0, 3.0) 8.00
sqrt(x) Square root of a number sqrt (4.0) 2.00

Some Commonly Used Trignometric Functions

Name Description Example Result
cos (rad) Cosine of an angle in radians cos(PI) -1.00
sin (rad) Sine of an angle in radians sin(PI) 0.00
tan (rad) Tangent of an angle in radians tan(PI / 4) 1.00

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);
    
  • 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;
    
  • Note that the function evaluates the sqrt(3.0 * 3) before adding it to 1.0
  • Functions have a higher precedence than arithmetic operators

Check Yourself

  1. The following code snippet prints ________.
    int x = -42;
    cout << abs(x);
    
  2. The value of x after following code snippet executes is ________.
    double x = pow(3, 2);
    
    1. 2
    2. 3
    3. 8
    4. 9
  3. The value of x after following code snippet executes is ________.
    double x = max(4, 2);
    x = sqrt(x * x);
    
    1. 2
    2. 4
    3. 8
    4. 16

More Information

  • Language Reference: Arduino documentation on core functions, including Math and Trigonometry
  • math.h: Arduino documentation on trignometric and exponential functions

Assignment Operators

  • As we discussed before, we assign values to variables using an equal (=) sign
    int sum = 0;
  • However, the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, we can have the same variable on both sides of an equals sign:
    int sum = 25;    // initialize sum to 25
    sum = sum + 10;  // add to sum
    
  • Note that the value of the variable is changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values: Assigning a value to a variable

Compound Assignment Operators

  • C/C++ has additional assignment operators that combine other operators with assignment
    • Known as compound assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is an operator like one of the five arithmetic operators: +, -, *, /, %
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are some assignment operators with examples of how they are used

Summary of Assignment Operators Used in Arithmetic Operations

Operator Description Example Equivalent To
= Assigns the value of the expression on the right to the variable on the left x = 3  
+= Adds the expression on the right to the variable on the left x += 3 x = x + 3
-= Subtracts the expression on the right from the variable on the left x -= 3 x = x - 3
*= Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left x *= 3 x = x * 3
/= Divides the variable on the left by the expression on the right and saves the result in the variable on the left x /= 3 x = x / 3
%= Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left x %= 3 x = x % 3

Increment and Decrement Operators

  • Adding or subtracting one is a common operation in programming
  • C/C++ provides arithmetic shortcuts for these operations with the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Preincrement adds 1 before evaluating an expression
    ++sum
  • Post-increment evaluates the expression and then adds 1
    sum++
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable:
    --sum
    sum--
    
  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    cout << "x=" << x << " y=" << y;
    
  • We may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

Check Yourself

  1. The value of count after the following code executes is ________.
    int count = 0;
    count = count + 1;
    
  2. What is an equivalent statement for each of the following shortcut assignments?
    1. a += b;
    2. a -= b;
    3. a *= b;
    4. a /= b;
    5. a %= b;
  3. List four ways to add the integer 1 to a variable named c.

Exercise 1: Calculator Deluxe

In this exercise we convert your Arduino into a deluxe calculator!

Parts

  • Arduino board
  • USB cable

Starter Code

#include <ArduinoSTL.h>

using namespace std;

void setup() {
  Serial.begin(9600);
  cout << "Enter two numbers separated by a space" << endl;
}

void loop() {
  int a; 
  int b;
  if (Serial.available()) {
    cin >> a >> b;
    cin.ignore(1);
    cout << "You entered: " << a << " and " << b << endl; 

    int numAdd = a + b;
    cout << "a + b = " << numAdd << endl;

    // add more arithmetic code here
    
  }
}
Specifications
  1. Start the Arduino IDE, copy the starter code above and paste it into the main IDE window.
  2. Save the project using the name calculator (File > Save As...) to a convenient location like the Desktop or the Arduino projects folder.
  3. Compile the sketch to verify you copied the starter code correctly.
  4. Upload the code and open the Serial Monitor to view the output.
  5. Add equivalent code for subtraction, multiplication, division and modulus. For example, here is the code for subtraction:
    int numSub = a - b;
    cout << "Subtraction: " << numSub << endl;
    

    Hint: copy and paste the above code and then modify the copied code for each type of operation.

  6. Compile and upload your code to verify it works correctly.

    You should now be able to see output like the following in the Serial Monitor:

    Enter two numbers separated by a space
    You entered: 3 and 2
    a + b = 5
    a - b = 1
    a * b = 6
    a / b = 1
    a % b = 1
    
  7. Attempt to change the data types of a and b as follows:
    double a; 
    double b;
    

    Why doesn't the calculator show you floating point numbers after making this change? What would you have to change to make it work? 

  8. Save your calculator.ino file to submit to Canvas with the next homework.

When finished, please help those around you.

Summary

  • C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, we use parenthesis
  • The results of integer division are truncated
  • We must use modulus operator (%) to get the remainder value
  • Modulus only works with integer data types, not floating-point types
  • To save typing, C++ has assignment variations of the form:
    variable <op>= expression;
  • For example, the following statements create the same result:
    c = c + 1;
    c += 1;
    c++;
    

Wrap Up and Reminders

  • When class is over, please shut down your computer.
  • Complete unfinished exercises from today before the next class meeting
Comments