CS 102/ECE 206 Lecture Notes: Chapter 2, Part 2C++ Programming

Arithmetic in C++

 + addition a + b - subtraction a - b * multiplication a * b / division a / b % modulo (mod) a % b

1. Integer division yields the quotient.
2. Modulo arithmetic yields the remainder.
3. The % operator requires integer operands.

Examples:  17 / 5 ---> 3 5 / 17 ---> 0 17 % 5 ---> 2 5 % 17 ---> 5

Addition and multiplication are used to build numbers up; subtraction, division, and modulo are used to break them apart. Remember these tools!

• Operator Precedence   (full table is in appendix)

 ( ) inside out high * / % left to right | + - left to right low

Example:  What is value of: 9 + 3 * 2 + 12 / 4 This is the same as: 9 + (3*2) + (12/4) 9 + 6 + 3 18   (not 9!!!)

Use parentheses liberally but sensibly!

• Mixed Mode Arithmetic and Data Type Hierarchy

Mix mode arithmetic involves calculations with mixed data types.
Highest mode determines the mode of the operation.

Data type hierarchy, high to low: 1) double   2) float   3) int

Examples:

20.5 / 5 ---> 4.1               5 is converted to 5.0
20 / 5.0 ---> 4.0               20 is converted to 20.0
20 / 6 * 2.0 ---> 6.0         Why?
2.0 * 20 / 6 ---> 6.667     Why?

Example:

```       double x, y;       y = 20 / 6;   // 20 / 6 is the integer 3, converted to 3.0       x = y * 5;    // 3.0 * 5, converted to 5.0       cout << "y = " << y << " and x = " << x << endl; ```

Output?       ``` y = 3 and x = 15       // Stored values are 3.0 and 15.0. ```

Rules of evaluating expressions in assignment statements:

1. Do right-hand-side using data type hierarchy.
2. Convert result to left-hand-side type.
3. Intermediate results follow type rules.

Example:

```       double x;       x = (4 * 2) + 24 / 5; ```

x is 12.0 because

4 * 2 ---> 8, an integer
24 / 5 ---> 4, an integer and performed before the addition
8 + 4 ---> 12, an integer
12 is converted to a double, 12.0.

Example:

``` x = (4 * 2) + 24.0 / 5; ```

4 * 2 ---> 8, an integer
24.0 / 5 ---> 4.8, a double
8 + 4.8 ---> 8.0 + 4.8 ---> 12.8, all doubles

Evaluate:

 1) 20.0 / 3 * 20 / 3 44.4444 2) 20.0 / (3*20) / 3 0.1111 3) 20 / 3 * 20 / 3 40 4) 20 / (3 * 20.0) / 3 0.1111 5) 20.0 / 3 + 20 / 3 12.6667 6) 20.0 / (3+20) / 3 0.2899

Notice that all but number three are doubles.

Changing Types

• int to double

If we add three integers and and want to compute the average, we cannot divide the integer sum by the integer 3 unless we want to truncate the fractional part of the average. There are several possible solutions. Assume variables average and sum are doubles and the others are integers.

``` Declare all variables to be doubles. sum = x + y + z;    average = sum / 3;      // mixed mode average = (x + y + z) / 3.0;                      // convert int 3 to double 3.0 average = (x * 1.0 + y + z) / 3;                // convert value of int x to a double ```
1. ```average = (double)(x + y + z) / 3;            // cast x to a double ```

• double to int
``` x = (int)sum;                  // cast sum; fractional part is lost ```
1. ```Write problem-specific code to avoid losing data. ```

More on assignment, trace tables, the what (not how)

Example:

```       int x, y, z;       x = 24; y = 6;       z = x;       x = y;       y = z;       cout << x << " " << y << endl; ```

WHAT (not how) does the code do?   Let's examine the trace table.

Trace Table
x
y
z

Shortcuts:    Learn

• Compound assignment:
`n = n + 5; `    or     `n += 5; ` `  // caution: order of precedent is low`
`n = n * 5;`     or     `n *= 5; ` `  // caution: order of precedent is low`

Also valid for   ``` -=   /=   %= ```

• Increment operator:   ` ++ `
` x++; `functionally equivalent to ` x = x + 1; `

• Decrement operator:   ` -- `
` x--; ` functionally equivalent to ` x = x - 1; `

• Multiple assignment:
` x = y = z = 0;       // right to left execution `
same as   ``` z = 0;   y = 0;   x = 0; ```
` `

Postfix vs. Prefix:

Postfix:   ` x++; ` Increment `x` after value of operand is obtained.
Prefix:     ` ++x; ` Increment `x` before value of operand is obtained.

Example:

```       x = 3;       y = x++; ```    y holds 3     x holds 4

Example:

```       x = 3;       y = ++x; ```     y holds 4     x holds 4

Example:

```       x = 3;       y = ++x + x; ```     Compiler dependent! (Also avoid in `cout` and function calls)

Program Execution

Recall:
The command   `g++ trial.cpp`     compiles and links the source code in file trial.cpp.
The command   `./a.out`       executes the program.
Input data comes from the keyboard; output goes to the monitor.

Example: ```   ./a.out < somefile ```

During execution, input is read from `somefile`.

Example: ```   ./a.out > otherfile ```

The output is written to `otherfile`.

Example: ```   ./a.out < somefile > otherfile ```

The input is read from `somefile` and the output is written to `otherfile`.

Errors

syntax error - Code violates grammar rules, and code doesn't compile. Fix the first error, others often disappear. Note: If your lab code does not compile, you will receive a zero for the problem.

run-time error - Code cannot run to completion; it has instructed the computer to perform an illegal operation.

logic error - Code terminates normally, but

1. produces incorrect results, or
2. does not solve the problem (faulty algorithm).

Example Problem, with casting:

Read in a sum of money and determine the number of quarters, dimes, nickels, and pennies represented in the cents portion. You must get an optimal mix; all pennies, for example, is not allowed. Let's write the algorithm first.

Example:

With input of   43.59   you should come up with 2 quarters, 1 nickel, 4 pennies. Variable cash is a double; the rest are integers. Note the use of casting in step 2.

 1 Read cash amount. 1 cin >> cash; 2 Isolate change, convert to int. 2 change = (int)(cash * 100) % 100; 3 Figure coins. 3 Refine this step. (below) 4 Display results. 4 See below.

Refine Step 3:

``` quarters = change / 25; dimes = (change - (quarters * 25)) / 10; nickels = (change - (quarters * 25) - (dimes * 10)) / 5; pennies = change % 5; ```

The code above is dependent on parentheses!!

``` quarters = change / 25;   // isolate quarters change = change % 25;     // remove quarters from change dimes = change / 10;      // isolate dimes change %= 10;             // remove dimes from change nickels = change / 5;     // isolate nickels pennies = change % 5;     // remove nickels; only pennies remain ```

Step 4: Display Results

The values depend on the input, but the form is:

In \$X.XX there are X quarters, X dimes, X nickels, and X pennies.

Click here to see the entire program. Note that to implement the alternate step 3, we must print the original value of `change` before we destroy it.

There is a problem, however. Because of the way the system stores floating point values, we may lose precision when we cast a floating point to an integer. This happens in this code with certain input values of less than one.

Think:  How would you display dollars only, not cents?

Lab 1 Revisited

Return to the coins problem from Lab 1. Can you see a better way to write the code? If not, think about it and return to it later.

Basics of Decision

• if ( )-else   is the basic binary decision control structure in C++.
• The six relational operators   are   <       >       ==         <=       >=      !=
• Logical expressions evaluate to zero (false) or non-zero (true).

Examples

``` const int FALSE = 0;```  `   if (6)   ` evaluates to   `!FALSE`   (true) `   if (0)   ` evaluates to   `FALSE` `   if (4 <= 3)  ` evaluates to   `FALSE` `   if (17 != 17)  ` evaluates to   `FALSE` `   if (6 == 6)  ` evaluates to   `!FALSE`   (true) `   if (15 > 10)  ` evaluates to   `!FALSE`   (true)

If an expression evaluates to 0, the expression is false; otherwise the expression is true (i.e., `!FALSE`). Syntax of simple if:

if (logical expression)   executable statement

Decision Examples

1.   if (change % 25 != 0)    cout << "There is a remainder.\n";

2.   if (change % 25)    cout << "There is a remainder.\n";          // functionally equivalent to statement above; study this line

3.   if (hours_passed >= 90)    cout << "You are a senior.\n";

4.   if (x == y)    cout << "x and y are equal.\n";

5.   cin >> temp_code >> degrees;
if (temp_code == 'c')
fahrenheit = 9.0 / 5 * degrees + 32;     // Why 9.0?   Why not 5.0?   Or 9?

6.   if (x % 2)    cout << x << " is odd.\n";
else     cout << x << " is even.\n";

Iteration  (Play it again, Sam...)

Loop constructs allow us to execute a code segment repeatedly, and the simplest loop form is the while loop.

General form of loop constructs:

 ``` // Comment to describe the function of the loop Loop Head < executable code > Return to Loop Head ```

Note: The comments before the loop head are for the benefit of the reader and are ignored by the compiler.

In general, a loop performs the following tasks:

1. initialization of variables
2. data modification
3. body of loop, may include data modification
4. a test for loop termination

while Loop

 ``` syntax (form): while(logical expression) statement ```

-----------------------------------
An aside. Variables of type char can hold a single character, and character constants are delimited by single quotes. We use the ASCII character set; see the table in your text. Note: a space is a valid character. To input a character into a char variable, you merely type the character; you do not enclose it in single quotes. Be aware that the ASCII character '4' is stored in one byte of memory and is different from the integer   4   which is stored in 2s-complement.

Example

 ``` char ch; // loop control variable (lcv), holds input char // skip leading blanks in the input stream cin >> ch; // prime read while(ch == ' ') cin >> ch; ```

Note:    while loops use pretesting. The logical expression is evaluated to true or false
to determine whether or not the loop body is executed.

Question:    What happens if we place a semi-colon after the loop header?   while(ch == '  ' );
Question:    What is the value of ch when the loop terminates?

Notice the syntax:

1. The logical expression is contained in parentheses;
2. there is no semi-colon after the expression;
3. there is only one statement executed if the expression is true;
that one statement may be a compound statement { }.

 ``` // include a comment to describe what loop does while(logical expression) { statement 1; statement 2; ... statement n; } ```

Question:    What happens if we place a semi-colon before the opening brace in the loop header?   while(logical expression) ;   {

Question:    What happens if we place a semi-colon after the opening brace in the loop header?   while(logical expression)   { ;

Example

Often we must "prime" the loop, such as with an initial or prime read before the loop head.

 ``` const int SENTINEL = -99999; ... int number; // holds individual input value // read and echo zero or more integers cout << "Enter an integer, -99999 to quit. "; cin >> number; while(number != SENTINEL) { cout << number << endl; cout << "Enter an integer, -99999 to quit. "; cin >> number; } ```

• What does this loop do?   (Not: How does it work?)
• What if the input stream does not contain the sentinel value -99999?
• What happens if -99999 is the first input value?
• What happens if   6   0   -99999   14   is the input?

Example

Write a code segment to skip over leading non-alphabetic characters in the input stream.

 ``` char ch; // holds input character, lcv // skip over leading non-alphabetic characters in input cin >> ch; while( !(ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') ) cin >> ch; ```

Question: What is (always) the value of  ch  when the loop terminates?

Is this good code? It is hard to read, and I would write the logical expression as a function, alphabetic( ). Then the code would be:

 ``` char ch; // holds input character, lcv // skip over leading non-alphabetic characters in input cin >> ch; while( !alphabetic(ch) ) cin >> ch; ```

Of course, we would include a prompt for input, but I didn't want to clutter the code.

Question: Can you write function alphabetic( )?

________________________________________

Note: You must alter the loop control variable, or lcv, during execution of the loop.
Below, we get trapped in an infinite loop when the input is negative.

 ``` int x; cin >> x; while(x < 0) cout << x << endl; ```

This is an infinite loop because the value of the lcv`  x ` is not modified in the body of the loop.
Thus, the stopping condition   `x >= 0`   may never be met.

Warning: Endless loops are (often) not cool.