## Lecture 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 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 (coins1.cpp)

Consider the following simple problem:
I have 8 pennies, 4 dimes, and 3 quarters in my purse. What is the total value of the coins?

• [d]
• 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. coins)
• Processed faster and require less storage space (than floating point numbers)
• Floating-point numbers (double) have decimal points (in US standard).
• Floating-point numbers are 1.2; 0.001; -0.12; 1e-2; 13E2; -2.9e-2; etc.

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.
• Use the asterisk * for multiplication (not dot or cross).
• Comments are denoted by /* comment text */ or // comment text
• Ignored by the compiler.
• Explains the program to other programmers or yourself.

Syntax 2.2: 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.
• Variables are locations in memory that can hold values of a particular type.
• Variable naming rules (symbolic names, identifiers):
• Names must start with a letter.
• Remaining characters are letters, digits or underscore_ (no spaces or special symbols)
• You cannot use reserved words (as int, return, etc.).
• Variable names are case-sensitive (e.g. Area and area are different names).
• To avoid any possible confusion we will never use any uppercase letters in variable names.
• Each variable has:
• Type (e.g. int or double)
• Name (e.g. pennies)
• Value (e.g. 8)

Syntax 2.3: Variable Definition Statement

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

## Input and Output (coins2.cpp)

The program could ask how many coins I have of any kind, and then compute the total.

• Input stream operator (>>) reads console input:

cin >> pennies;

• The program waits for the user to type in a number and Enter key.
• The number is placed into the variable, and the program executes the next statement.
• If user doesn't enter appropriate input, then the stream fails (sets cin in "failed" state). All subsequent input also fails.
• [d]
• Can read multiple values:

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

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

8 0 4 3

or

`8043`
• Input is buffered. If you type two inputs on one line, the second one is saved for the next input statement.
• [d]

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.

## Assignment (coins3.cpp)

Let us compute the value of the coins by keeping a running total.

## 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;`
• Compute the value of the nickel contribution, add to it the value of the running total, and place the result again into the variable (memory location) total.
• Do not confuse the assignment operation with algebraic equality.

Syntax 2.5: Assignment

`variable = expression;`
 Example: `total = pennies * 0.01;` Purpose: Store the value of an expression in a variable.

## 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 (volume1.cpp)

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

## Constants (volume2.cpp)

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.

## Arithmetic

• 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
• In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
`9.0 / 4.0   /* 2.25 */9 / 4.0     /* 2.25 */9.0 / 4     /* 2.25 */`
• If both numbers are integers, then the result is an integer:
`9 / 4      /* 2 Attention! */`
• To get the remainder of (integer) division between two integers, use the modulus operator %:
`9 % 4      /* 1 remainder */`

## Arithmetic (coins4.cpp)

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|

## Strings

• A string is a sequence of characters.
• To use the string type, include the header file for strings: #include<string>.
• C++ strings 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 initializationname = "Carl";        // assignmentcout << name << ", please enter your name:"; // outputcin >> 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

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 (Output Formatting)

• Unformatted output:
`cout << pennies << " " << pennies * 0.01 << "\n";cout << nickels << " " << nickels * 0.05<< "\n";cout << dimes << " " << dimes * 0.1 << "\n";cout << quarters << " " << quarters * 0.25 << "\n";`
will produce (form1.cpp):
` 1 0.01 12 0.60 4 0.40 120 30.00`
• 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 zeros are displayed.
• The sequence of commands
`cout << fixed << setprecision(2);cout << setw(8) << pennies << " "     << setw(8) << pennies * 0.01 << "\n";cout << setw(8) << nickels << " "     << setw(8) << nickels * 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 (form2.cpp):
`       1     0.01      12     0.60       4     0.40     120    30.00`