What We Will Cover
Continuations
Homework Questions?
Questions from last class?
^ top
2.1: Basic Coding Skills
Objectives
At the end of the lesson the student will be able to:
- Write appropriate comments in programs
- List the rules for creating an identifier
- Identify statements in programs
- Include libraries and use namespaces in programs
- Code
main functions
|
^ top
2.1.1: Comments
- Comments are ... comments -- notes to people reading the code
- Comments ignored by compiler
- Use comments to document and describe code
- Comments can start with
// and last to end of the line
// this is a comment
Comments can span multiple lines: /* ... */
/* This is a multi-line comment
which can be split
over many lines or a portion of one line. */
Programming Style: Block Comments
- Use block comments like the following at the start of a program file
/**
* CS-11 Asn 0
* hello.cpp
* Purpose: Prints a message to the screen.
*
* @author Jane User
* @version 1.0 8/20/03
*/
^ top
2.1.2: Statements
- Statements direct the operation of the program
- Most statements end in a semicolon (
;)
cout << "Hello, world!";
However, statements requiring a set of braces {} end with the right brace
int main() {
cout << "Hello, world!";
}
Note that we can have multiple statements within a pair of curly braces
Programming Style: Line Length
- Limit your line length to 80 characters
- Longer lines can cause problems with many text editors and other tools
^ top
2.1.3: Identifiers
Identifier - the name of a variable, procedure, class or other programming construct.
- Purpose of an identifier is to provide a name for something
- Programmers create identifiers for the names of many things in a program:
- variables
- functions
- files
- classes
- Identifiers are made up of a sequence of characters
- Each character can be a:
- Letter
- Digit
- Underscore:
_
- Dollar sign:
$
- Can not start with a digit
- Can not contain any periods or spaces
- Can not be a keyword (e.g. "
if, "for", etc.: see C/C++ Keywords)
- Are cAsE sEnSiTiVe!
id, ID, iD and Id are all valid but different identifiers
- Programming style: identifiers have naming conventions
- You must follow these naming conventions on your homework
Keywords
- Keywords are reserved words with predefined meanings
- We used keywords in our
hello.cpp program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
All keywords have special meaning in C++
- Can only be used for their specified purpose
- Attempting to use for any other purpose will generate a compiler error
- Thus cannot use keywords as identifiers
For a current list, see C/C++ Keywords
Note that the entire C++ language has only about 62 keywords
Part of learning a language is learning what the words mean
^ top
2.1.4: Libraries and Namespaces
- C++ has a number of standard libraries
- These libraries place their definitions in a namespace
Libraries and include Directives
- Use the include directive to add the contents of a library to your program
#include <libraryName>
Called a ‘preprocessor directive’
Executes before compiling, and ‘copies’ a library into your program file
Most of our programs begin with a declaration like:
#include <iostream>
Which is a library for console I/O
Other libraries exist for math, strings and more
Note that some compilers are picky about spaces in include directives
- Do not put spaces before or after the
# sign
- Do not put spaces inside the angle brackets
Namespaces
- Namespace: a collection of name definitions
- You can only use a name once within a namespace
- All standard libraries put their definition in the namespace:
std
- To use these standard names, you need the directive:
using namespace std;
Thus, most of your programs will begin with two declarations:
#include <iostream>
using namespace std;
^ top
2.1.5: Declaring a main Function
- Function - a block of code that performs a task
- Every C++ program has one or more functions
- Every C++ application has a main function that is declared like this:
int main() {
// function definition goes here
}
Programs begin executing at the main function
int means main returns a value of type int -- cover later
For now, mimic the first line of main
Left brace { begins body of every function
Right brace } ends body of every function
Last statement in main should be a return statement
return 0;
^ top
2.1.6: Summary
- C++ has two styles of comments
- Comments help document what a program does
- Use block comments at beginning of file and before functions
- Otherwise, use them sparingly
- Statements direct what a program does
- Identifiers are any name you create in a C++ program
- Keyword is a special word reserved by C++
- Cannot use a reserved word as an identifier
- C++ has standard libraries of prewritten code
- Definitions for these libraries are collected in a namespace called:
std
- Thus, most of your programs will begin with two declarations:
#include <iostream>
using namespace std;
Every C++ application starts with a function named main
^ top
Exercise 2.1
With a single partner, if needed, take 5 minutes to complete the following:
- Start a text file named exercise2.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 2.1
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise2.txt.
Exercises and Questions
- Start your text editor and enter the following code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
- Save the file as "hello.cpp".
Q1: Which lines of code contain an identifier?
- Compile and execute the code.
g++ -W -Wall --pedantic -o hello hello.cpp
Q2: Which lines of code end a statement? How can you tell?
- Add a block comment as shown in section 2.1.1
- Re-compile and execute the code.
Q3: How does the added block comment change the execution of the code?
- Remove the directive:
using namespace std; and then re-compile the code.
Q4: What message does the compiler report?
^ top
2.2: Data and Data Types
Objectives
At the end of the lesson the student will be able to:
- Describe the C++ primitive data types
- Distinguish between an integer, a floating-point number, and a boolean value
- Decide which data type is appropriate for representing data
|
^ top
2.2.1: Bits and Bytes
"There are only 10 kinds of people in the world, those who understand binary and those who don't."
-- Unknown
- Bit - (Binary Digit) smallest unit of information within a computer
- Bit has two values: 0 and 1
- How do we represent the value "2" in binary?
- Byte - a group of 8 bits
- Usually the smallest addressable amount of memory
- A byte has 256 possible combinations of values -- Why 256?

- What is the binary number represented by the picture above?
- What is the decimal equivalent?
- How do you think computers store the following data?
- 12
- 512
- 1.23
- 3.14159...
- The letter 'A'
- The boolean values
true or false
More Information
^ top
2.2.2: Primitive Data Types
- C++ has built-in data types for numbers, characters and booleans
- These built-in types are called primitive types
- A data type tells a computer how to interpret the data
- C++ can recognize literal values for each primitive type
- Literal values are a sequence of characters in a certain form
| General Type |
Explanation |
Examples |
| Integers |
Numbers without decimal points |
123 -987 |
| Floating-Point |
Numbers with decimal points |
1.23 -0.01 |
| Characters |
Single letters, digits and special symbols |
'A' '9' |
| Booleans |
Logical values true or false |
true false |
- Since these literal values are compiled into our programs, they cannot be changed
^ top
2.2.3: Integers
- An integer is zero or any positive or negative number without a decimal point
- For example:
0 1 -1 +5 -27 1000 -128
Integer literals may have a sign (+ or -) before the number
Cannot have any commas, decimal points or special symbols (like $)
Integer Data Types
- Some C++ integer data types are:
| Type Name |
Memory Size |
Range of Values |
short |
2 bytes |
-32768 to 32767 |
int |
4 bytes |
-2,147,483,647 to 2,147,483,647 |
long |
4 bytes |
-2,147,483,647 to 2,147,483,647 |
- In C++, you may add these modifiers to the type:
signed
unsigned
short
long
^ top
2.2.4: Floating-Point Numbers
- A floating-point literal 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
Like integers, cannot have any commas or special symbols
Floating-Point Data Types
- Some C++ floating-point data types are:
| Type Name |
Memory Size |
Range of Values |
float |
4 bytes |
about ±1.4 x 10-45 to ±3.4 x 1038 |
double |
8 bytes |
about ±3.4 x 10-308 to ±1.7 x 10308 |
Exponential Notation
- Floating-point literals can be written in exponential notation
- Similar to scientific notation
- Used to express both very large and very small values in compact form
- For example:
| Decimal Notation |
Exponential Notation |
Scientific Notation |
| 1234 |
1.234E3 |
1.234 x 103 |
| 98765 |
9.87654E4 |
9.8765 x 104 |
| 0.0123 |
1.23E-2 |
1.23 x 10-2 |
| 0.000625 |
6.25E-4 |
6.25 x 10-4 |
- Letter
E stands for exponent
- Number following
E represents a power of 10
- Indicates the number of decimal places to move for standard decimal value
How Large is 1.7E308?
- Largest possible
double is 17 followed by 307 zeros
- How large is that?
- Current estimate of the number of atoms in the universe: about
1.0E78
- Mathematicians use the term "google" for a very large number:
1.0E100
- Data type
double easily encompasses these numbers
- What value cannot be represented by type
double?
^ top
2.2.5: Characters
- A character is a letter, number or special symbol
- For example:
'a' 'b' 'Z' '3' 'q' '$' '*'
C++ provides the char data type to represent characters
Stores characters as an 8-bit unsigned value using ASCII
Escape Sequences
- First 32 character codes are not visible on our monitors
- C++ can access some of the control codes using escape sequences
- Backslash (
\) directly in front of a certain character tells the compiler to escape from the normal interpretation
- Following table has some nonprinting and hard-to-print characters:
| Sequence |
Meaning |
\a |
Alert (sound alert noise) |
\b |
Backspace |
\f |
Form feed |
\n |
New line |
\r |
Carriage return |
\t |
Horizontal tab |
\\ |
Backslash |
\" |
Double quote |
\' |
Single quote |
- Some examples:
cout << '\a' << endl; // alert
cout << '\n' << endl;
cout << "Left \t Right" << endl;
cout << "one\ntwo\nthree" << endl;
Programming Style
^ top
2.2.6: Boolean Values
- Boolean types have just one of two values: either
true or false
- Mostly used in conditional statements -- will cover later in course
cout << true << endl;
cout << false << endl;
cout << boolalpha; // show output as true or false
cout << true << endl;
cout << false << endl;
^ top
2.2.7: Summary
- Computers store data in units of 8 bits called a byte
- Some primitive C++ data types are:
| Type |
Bytes |
Use |
| char |
1 |
All ASCII characters. |
| short |
2 |
Short integers from -32,768 to 32,767. |
| int |
4 |
Integers from -2,147,483,647 to 2,147,483,647. |
| long |
4 |
Integers from -2,147,483,647 to 2,147,483,647. |
| float |
4 |
Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits. |
| double |
8 |
Double-precision, floating-point numbers from E-308 to
E308 with from 14 to 15 significant digits. |
| bool |
1 |
A true or false value. |
- Note that number of bytes used for storage depends on the system and compiler
^ top
Exercise 2.2
Determine the data types that are appropriate for the following problems and record your answers in exercise2.txt:
- The average number of four grades
- The number of days in a month
- The length of the Golden Gate Bridge
- The numbers in the state lottery
^ top
2.3: Arithmetic
Objectives
At the end of the lesson the student will be able to:
- Use arithmetic operators
- Perform integer division and use the modulus operator
- Translate algebraic expressions into C++ code
|
^ top
2.3.1: Arithmetic Operators
- Can perform arithmetic on integers and floating-point numbers
- Use special symbols to perform the operations:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- For example:
3 + 4
12 - 7
12.3 + 4.56
.065 * 1200
18 / 2
17.4 / 2.3
These combination of numbers and operators are called arithmetic expressions
Expressions are parts of a program that return a value
We can use these expressions to perform arithmetic and display the results
cout << 3 + 4; // prints 7
Negation
- Operators
+, -, *, /, % are called binary operators
- Always need two operands (numbers) to work with them
- C++ also provides a unary operator:
- (minus sign)
- Reverses the sign of a number
- For example:
-1 -5.3 - -1
C++ also provides a plus sign (+) unary operator
^ top
2.3.2: Mixed-Mode Expressions
- Recall the different data types are stored in different forms
- Computer needs both operands in the same form before it can perform an operation
- If one operand is different than the other, the compiler converts it to a wider type
- For example:
2 + 2.2
First number (2) is an int
Second number (2.2) is a double
First number is narrowest, thus gets promoted to a double (i.e. 2.0)
Then the arithmetic operation can take place to produce a result of 4.2
^ top
2.3.3: Integer Division and Modulus
- Dividing two integers can produce unexpected results for the unwary
- For example, what is the result of the following expression?
7 / 2
Since both numbers are of type int, one does not get a floating-point result
Remainder portion is truncated (discarded, thrown away)
Modulus Operator
- Sometimes you want to know the remainder of an integer division
- C++ provides the modulus operator:
% (percent sign)
- Returns the remainder of the division of first number by the second
- For example:
7 % 2 // returns 1
7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2
Check Ourselves
What is the result of the following arithmetic operations?
- 9 / 4
- 17 / 3
- 14 / 2
- 9 % 4
- 17 % 3
- 14 % 2
^ top
2.3.4: Arithmetic Precision and Range
- There are only a finite set of numbers in numerical data types
- Can lead to problems for the unwary
Integer Overflow
- What happens when an integer is too big for its type?
cout << "Big number: ";
cout << 2147483647 + 1 << endl;
cout << "Small number: ";
cout << -2147483647 - 2 << endl;
Wraps around from the highest number to the lowest
Must be careful that your program will not go beyond the range of its data types
Floating-Point Precision and Range
- Floating-point numbers are not exact representations of real numbers
- Rounding errors occur in repeated calculations
- Type double has about twice the precision of type float
- However, even type double can have rounding errors
cout.precision(17);
cout << .8F + .1F << endl;
cout << .8 + .1 << endl;
When floating point numbers get too large, they are set to inf
cout << 2E38F + 2E38F << endl;
Similarly, when too small they are set to 0.0
^ top
2.3.5: Operator Precedence and Associativity
- Often need to process expressions of greater complexity than two numbers
- May need more than one operator
- C++ has certain rules that must be followed
C++ Rules
- Two binary operators cannot be placed side by side
- Invalid expression:
5 * % 6
- Operators
* and % cannot be next to each other
- Parenthesis can be used to group expressions
- Anything within parenthesis is evaluated first
- Can have parenthesis within parenthesis
- Innermost parenthesis evaluated first
- Parenthesis cannot be used to indicate multiplication
- Programming style: add spaces around operators
- Programming style: no spacing after opening or before closing parenthesis
Precedence and Associativity Rules
- Arithmetic operators processed in algebraic order:
- Parenthesis:
( )
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- Addition, subtraction:
+, -
- Binary operators of same precedence evaluated from left to right
Examples of Expressions
| Algebra Expression |
C++ Expression |
Fully Parenthesized |
| 2(10 + 5) |
2 * (10 + 5) |
(2 * (10 + 5)) |
1
12.2 + 3 · 7.3 |
1 / (12.2 + 3 * 7.3) |
(1 / (12.2 + (3 * 7.3))) |
10 - 7
3.3 + 9 · 1.6
|
(10 - 7) / (3.3 + 9 * 1.6) |
((10 - 7) / (3.3 +(9 * 1.6))) |
| 2 · 42 |
2 * 4 * 4 |
((2 * 4) * 4) |
^ top
2.3.6: Mathematical functions
- Only the simplest mathematical operations are provided by operators
- For more complex operations, you use mathematical functions
cout << sqrt(9.0) << endl;
C++ provides a standard cmath library that contains many such functions
| Name |
Description |
Example |
Result |
| abs |
absolute value |
abs(-3.9) abs(3.9) |
3.9 3.9 |
| exp |
exponent |
exp(1.0) |
2.718... |
| log |
natural log |
log(10.0) |
2.40... |
| pow |
powers |
pow(2.0, 3.0) |
8.0 |
| sqrt |
square root |
sqrt(4.0) |
2.0 |
In addition, it includes two similar functions: ceil, and floor
| Name |
Description |
Example |
Result |
| ceil |
ceiling: round up |
ceil(3.3) ceil(3.7) |
4.0 4.0 |
| floor |
floor: round down |
floor(3.3) floor(3.7) |
3.0 3.0 |
Both return whole numbers, although they are of type double
To use the cmath library, you must include it in your source code file
#include <cmath>
using namespace std;
^ top
2.3.7: Summary
- C++ uses the following operators for arithmetic
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- Arithmetic expressions are combinations of numbers and operators
- Results of integer division are truncated
- Must use modulus operator (
%) to get the remainder value
- The dash (minus sign) is used for negation
- Operators have the same precedence as in algebra
- Parenthesis:
( )
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- Addition, subtraction:
+, -
- Multiplication operator always required, unlike algebra
- More complex mathematical operations are available using the cmath library
^ top
Exercise 2.3
Through the miracles of modern computer technology, we will now convert your $1000 computer into a $10 calculator!
- Copy the following program into a text editor; compile and run the program.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
- Replace the
"Hello, World!" portion of the program with the arithmetic expression 7 + 2 and then recompile and run the program.
Q1: What value was displayed by the computer?
- Use the expression
7 / 2 and then recompile and run the program.
Q2: What value was displayed by the computer? Why?
- Change the expression to use
7 % 2 and then recompile and run the program.
Q3: What value was displayed by the computer? Why?
- The following are algebraic expressions and an incorrect translation to code. Find the errors and write corrected code. Save the corrected expressions in
exercise2.txt.
| Algebraic Expression |
Incorrect Conversion |
| (2)(3) + (4)(5) |
(2)(3) + (4)(5) |
6 + 18
2 |
6 + 18 / 2 |
|
|
5 / 9 * (100 - 32) |
| 2 · 42 |
2 * 4 ^ 2 |
^ top
2.4: Variables and Declarations
Objectives
At the end of the lesson the student will be able to:
- Use declaration statements to declare variables
- Assign values to variables
|
^ top
2.4.1: Memory Addresses and Data Storage
- Computer data is stored in and retrieved from memory
- Before high-level languages, memory was referred to by its address
- Storing integers 45 and 12 would allocate memory like the following

- Quickly becomes cumbersome to write such programs
- Have to manually keep track of each location
- Have to make sure locations do not overlap
- More intuitive to assign each variable a name
- Let the computer remember the actual memory location
- Then each memory location can be referred to by name

- Now our programs can look like the following:
num1 = 45;
num2 = 12;
total = num1 + num2;
Each of these statements is called an assignment statement
Tells the computer to assign (store) a value into a variable
Assignment statements always have a variable name followed by an equal (=) sign
To the right of the equals sign is an expression that yields a value
^ top
2.4.2: Declaring Variables
- Declaration statement both names a variable and specifies the data type it can store
- All C++ program variables must be declared before using them
- General syntax:
dataType VariableName1, VariableName2, ...;
For example:
int num1, num2, total;
long dateNum;
float firstNum;
double secNum;
char letter;
When variables are declared, computer allocates storage space
Amount of storage space depends on the data type
Contents of the storage space is undefined until a value is assigned
| Type |
Bytes |
Use |
| char |
1 |
All ASCII characters. |
| short |
2 |
Short integers from -32,768 to 32,767. |
| int |
4 |
Integers from -2,147,483,647 to 2,147,483,647. |
| long |
4 |
Integers from -2,147,483,647 to 2,147,483,647. |
| float |
4 |
Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits. |
| double |
8 |
Double-precision, floating-point numbers from E-308 to
E308 with from 14 to 15 significant digits. |
| bool |
1 |
A true or false value. |
- Use meaningful names that are easy to remember as you code.
- Two commonly-used styles you may use
- Start with a lower-case letter and use uppercase letters as separators. Do not use underbars (
'_').
int myVar
- Use all lower case letters and use underbars (
'_') as separators.
int my_var
- You must be consistent and only use one of them in a program.
- The instructor's preference is the first style.
^ top
2.4.3: Assigning Values to Variables
- Use the assignment operator "equals sign" (
=)
variable = expression;
Assigns value of expression (right side) to the variable (left side)
The simplest expression is a literal value:
length = 25;
width = 17.5;
In each statement, value on right is assigned to the variable on the left
Can also assign results of more complex expressions to a variable
total = num1 + num2;
slope = (y2 - y1) / (x2 - x1);
Assigning Initial Values to Variables
- Initial values may or may not be assigned when variables are declared:
// These are not initialized when declared
// and have unknown values
int sum, number1, number2;
// These are initialized when declared
int sum = 0;
int number1 = 5, number2 = 10;
Good programming practice: initialize variables when declared
Programming Style: Constant Variables and Magic Numbers
- The meaning of literal numbers is hard to remember
- Sometimes called "magic" numbers"
- Magic because no one has a clue what it means after 3 months, including the author
- A better approach is to assign the number to a descriptive constant variable
- C++ uses the keyword
const to indicate a variable that cannot change
const int MY_CONST = 1;
Note that the name is all uppercase letters with an underscore separator
This is a common coding convention that you must follow
^ top
2.4.4: Assignment Variations
- You 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 changed in the second line
Reading variables from memory does not change them
Values placed into a variable replace (overwrite) previous values

Abbreviated Assignment Expressions
- Any statement of form:
variable = variable <op> (expression);
- May be written in an abbreviated form:
variable <op>= expression;
<op> is one of: +, -, *, /, or %
- For example:
sum = sum + 10;
Can be written as:
sum += 10;
Incrementing and Decrementing
- Adding 1 to a number occurs frequently when programming
count = count + 1;
You can write this in an abbreviated form like:
count += 1;
Since it is so common, programmers wanted an even shorter form:
count++;
This is known as incrementing a variable
Similarly, you can decrement a variable
count--;
^ top
2.4.5: Type Casting
Cast: change the data type of the returned value of an expression
- Recall that different data types are stored in different forms
- Sometimes need to change from one form to another
- Example: arithmetic adding a double and an int value
- C++ will automatically cast one value to another
- Also known as implicit casting
- May not know how to convert some values
- May not cast how the programmer wants
- Programmers can also explicitly cast data types
- Explicit casting changes the data type for a single use of the variable
- Precede the variable name with the new data type in parentheses:
(<dataType>) variableName
Data type is changed only for the single use of the returned value
For example:
int n;
double x = 2.0;
n = (int) x;
Value of x is converted from type double to integer before assigning the value to n
New Style Casting
- C++ has many styles of casting
- Newer style of casting is of the form:
static_cast<toType>(expression)
For example:
int x = 9;
int y = 2;
double ans = x / static_cast<double>(y)
Casting a char to an int
- Casting a
char value to int produces the ASCII value
- For example, what would the following display?
char answer = 'y';
cout << answer;
cout << (int) answer;
Answer:
>y
>89
Truncation When Casting Floating-Point to Integer type
- Converting (casting) a floating-point to integer type does not round -- it truncates
- Fractional part is lost (discarded, ignored, thrown away)
- For example:
int n;
double x = 3.99999;
n = (int) x; // x truncated
Value of n is 3
^ top
2.4.6: Summary
- Variables store a value that can change as a program executes.
- Constants store a value that cannot change.
- Variables and constants must be declared before use.
- To initialize a variable or constant, declare a name and assign a value.
- Simple assignment statements have a variable, equals sign and an expression.
variable = expression;
The expression is computed before the assignment
C++ has assignment variations of the form:
variable <op>= expression;
C++ will automatically cast data of one type to another when necessary
You can explicitly cast values of an expression to a different type.
You must use an explicit cast when C++ does not perform as you want.
^ top
Exercise 2.4
Recall the data that we explored in previous exercises:
- The average number of four grades
- The number of days in a month
- The length of the Golden Gate Bridge
- The numbers in the state lottery
Write a program for one of these that:
- Declares one or more variables
- Initializes the variable(s) with any value you like
- Prints the variable(s) to the screen
Submit your code along with exercise2.txt as a separate file.
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: October 20 2004 @11:41:46
|