## Chapter 2: Fundamental Data Types

## Chapter Goals

- To understand integer and floating point numbers
- To write arithmetic expressions in C++
- To appreciate the importance of comments and good code layout
- To be able to define and initialize variables and constants
- To recognize the limitations of the `int` and `double` types and the overflow and roundoff errors that can result
- To be able to change the values of variables through assignment
- To use the standard C++ `string` type to define and manipulate character strings
- To be able to write simple programs that read numbers and text, process the input, and display the results

## Number Types

- Integer numbers (`int`) are whole numbers without a fractional part.
  - Includes zero and negative numbers.
  - Used for storing values that are conceptually whole numbers (e.g. pennies).
  - Processed faster and require less storage space.
- Floating-point numbers (`double`) have decimal points.

## Number Types (coins1.cpp)

## Number Types (Syntax 2.1: Output Statement)

Syntax 2.1 : Output Statement
    cout << expression1 << expressioun2 << ... << expressionn;
Example: |
    cout << pennies;
    cout << "Total value = " << total << "\n";
Purpose: | Prints the values of one or more expressions.

## Number Types

- Use the asterisk * for multiplication (not dot or cross).
- Comments are denoted by `/* comment text */`
  - Ignored by the compiler.
  - Explains the program to other programmers or yourself.
- Variable naming rules:
- Names must start with a letter.
  - Remaining characters are letters or underscore (`_`) (no spaces or special symbols)
  - You cannot use reserved words.
  - Variable names are case-sensitive.

## Number Types (Syntax 2.2: Variable Definition)

Syntax 2.2 : Variable Definition
    type_name variable_name;
    type_name variable_name = initial_value;
Example: |
    int pennies = 8;
    double total;
Purpose: | Defines a new variable of a particular type, and optionally supply an initial value.

## Number Types (Syntax 2.3: Comment)

Syntax 2.3 : Comments
    /* comment text */
    // comment text
Example: |
    /* total value of coins */
    // total value of coins
Purpose: | Add a comment to help the human reader understand the program.

## Input and Output

- `>>` operator reads console input:

  > `cin >> pennies;`

- If user doesn't enter appropriate input, then the stream fails. All subsequent input also fails.
- Can read multiple values:

  > `cin >> pennies >> nickels >> dimes >> quarters;`

- User enters input separated by spaces or newlines, e.g.

  > `8 0 4 3`

  or

>     8
>     0
>     4
>     3

- Input is buffered. If you type two inputs on one line, the second one is saved for the next input statement.

## Input and Output (Syntax 2.4: Input Statement)

Syntax 2.4 : Input Statement
    cin >> variable1 >> variable2 >> ... >> variablen;
Example: |
    cin >> pennies;
    cin >> first >> middle >> last;
Purpose: | Read the value for one or more variables in from the console.

## Input and Output (coins3.cpp)

## Assignment (Syntax 2.5 : Assignment)

Syntax 2.5 : Assignment
    variable = expression;
Example: |
    total = pennies * 0.01;
Purpose: | Store the value of an expression in a variable.

## Assignment (Assignment Operator)

- `=` operator assigns the value of the expression on the right to the variable on the left.

  >     total = pennies * 0.01;
  >     total = count * 0.05 + total;

- Do not confuse the assignment operation with algebraic equality.

## Assignment (Increment and Decrement)

- Assignments like `month = month + 1;` are very common in programming.

- This assignment increments the variable month.
- C++ uses a special shorthand for increment:

  > `month++; // add 1 to month`

- C++ also supports decrement:

  > `month--; // subtract 1 from month`

## Constants (Syntax 2.7 : Constant Definition)

Syntax 2.7 : Constant Definition
    const type_name constant_name = initial_value;
Example: |
    const double LITER_PER_OZ = 0.029586
Purpose: | Define a new constant of a particular type and supply its value.

## Constants (volume2.cpp)

## Constants

- Giving symbolic names to constants makes programs easier to read and modify.
- Example: Suppose you switch from 2-liter bottle to half gallon bottles:
  - Must find every 2 in program.
  - Decide if number represents bottle volume, or something else
  - Replace with 1.893 if appropriate.
- Constants mean only changing a program at one location.

## Arithmetic (Basic Operations)

- All four basic arithmetic operations are supported by C++:
  - Addition and subtraction: `+ -`
  - Multiplication and division: `* /`
- Multiplication and division bind more strongly than addition and subtraction.
- Use parentheses to indicate the order in which the subexpressions should be evaluated.

  > | `a + b / 2`
  > | `( a + b ) / 2`

## Arithmetic (Integer Division)

- In division, if at least one of the numbers is a floating-point number, the result is a floating point number:

      7.0 / 4.0   /* 1.75 */
      7 / 4.0     /* 1.75 */
      7.0 / 4     /* 1.75 */

- If both numbers are integers, then the result is an integer:

      7 / 4      /* 1 */

- To get the remainder of division between two integers, use the modulus operator `%`:

      7 % 4      /* 3 remainder */

## Arithmetic (coins5.cpp)

## Arithmetic (Syntax 2.8 : Function Call)

Syntax 2.8 : Function Call
    function_name(expression1,expressioun2, ..., expressionn);
Example: |
    sqrt(x)
    pow(z + y, n)
Purpose: | The result of calling a function and supplying the values for the function parameters.

## Arithmetic (cmath Library Functions)

> Function | Description
> `sqrt(x)` | square root of x
> `pow(x, y)` | xy
> `sin(x)` | sine of x (in radians)
> `cos(x)` | cosine of x (in radians)
> `tan(x)` | tangent of x (in radians)
> `exp(x)` | ex
> `log(x)` | (natural log) ln(x), x > 0
> `log10(x)` | (decimal log) lg(x), x > 0
> `ceil(x)` | smallest integer >= x
> `floor(x)` | largest integer <= x
> `fabs(x)` | absolute value |x|

## Arithmetic (Analyzing an Expression)

## Strings

- To use the `string` type, include the header file for `string`s: `#include<string>`.
- C++ `string`s are enclosed in quotes, which are not part of the `string`.
- The string type behaves like number types with respect to declaration, assignment, output and input:

  >     string name = "John"; // declaration and initialization
  >     name = "Carl"; // assignment
  >     cout << "Please enter your name:"; // output
  >     cin >> name; // input (stops at first space)

- Use the statement

  > `getline(cin, name);`

  to read all keystrokes until the `Enter` key; e.g. should the user type

  > `Harry Hacker`

## Strings (Member Functions)

- The number of characters in a string is called the length of the string.
- You can compute the length of the string using the `length()` function.
- The length function is a member function, and must be invoked using the dot notation.

> Name | Purpose
> `s.length()` | The length of `s`
> `s.substr(i, n)` | The substring of length `n` of `s` starting at index `i`
> `getline(f, s)` | Read `string` `s` from the input stream `f`

## Strings (Syntax 2.9 : Member Function Call)

Syntax 2.9 : Member Function Call
    expression.function_name(expression1,expressioun2, ..., expressionn)
Example: |
    name.length()
    name.substr(0, n - 1)
Purpose: | The result of calling a function and supplying the values for the function parameters.

## Strings (Substrings)

- The `substr(start, length)` member function is used to extract substrings.

  >     string greeting = "Hello, World!\n";
  >     string sub = greeting.substr(0,4);
  >     /* sub is "Hell" */

- The position numbers in a string start at 0. The last character is always one less than the length of the string.

  > `H` | `e` | `l` | `l` | `o` | `,` | `` | `W` | `o` | `r` | `l` | `d` | `!` | `\n`
  > 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13

- `string w = greeting.substr(7, 5);`

  > `H` | `e` | `l` | `l` | `o` | `,` | `` | `W` | `o` | `r` | `l` | `d` | `!` | `\n`
  > 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13

## Strings (Concatenation)

- The + operator concatenates two strings.

  >     string fname = "Harry";
  >     string lname = "Hacker";
  >     string name = fname + " " + lname;

- One or both strings surrounding the + must be a variable.

## Strings (initials.cpp)

## Strings (Output Formatting)

- To format output we use the manipulators accessed by including `#include<iomanip>`.
- The `setw()` manipulator sets the field width of the next output.
- The `setprecision()` manipulator is used to set the precision of the next floating point number.
- By using the `fixed` manipulator, you ensure that trailing zeroes are displayed.
- The sequence of commands

  >     cout << fixed << setprecision(2);
  >     cout << setw(8) << pennies << " "
  >       << setw(8) << pennies * 0.01 << "\n";
  >     cout << setw(8) << nickles<< " "
  >       << setw(8) << nickles * 0.05<< "\n";
  >     cout << setw(8) << dimes<< " "
  >       << setw(8) << dimes * 0.1 << "\n";
  >     cout << setw(8) << quarters<< " "
  >       << setw(8) << quarters * 0.25 << "\n";

  creates the table

  >            1     0.01
  >           12     0.60
  >            4     0.40
  >          120    30.00