What We Will Cover
Continuations
Homework Questions?
Viewing WebCT Assignment and Exercise Results
Questions from last class?
What is the value of degreesC after the following statements execute?
double degreesC, degreesF;
degreesF = 122;
degreesC = 5 / 9 * (degreesF - 32);
0
0.0
50
50.0
^ top
3.1: More Math and Variables
Objectives
At the end of the lesson the student will be able to:
- Rewrite assignment statements into shortcut alternatives
- Diagnose problems with arithmetic precision and range and formulate solutions
- Generate code to convert data from one type to another
|
^ top
3.1.1: Review of Arithmetic
- Recall that C++ uses the following operators for arithmetic
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus (remainder)
- The dash (minus sign) is also used for negation
- Arithmetic expressions are combinations of numbers, variables, constants and operators
double area = 0.0, radius = 4.5;
const double PI = 3.14159;
area = PI * radius * radius;
Operators have the same precedence as in algebra
- Parenthesis:
( )
- Function calls
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- Addition, subtraction:
+, -
Also recall that the results of integer division are truncated
You must use modulus operator (%) to get the remainder value
In addition, you use mathematical functions for more complex operations
cout << sqrt(3.0 * 3) << endl;
^ top
3.1.2: Magic Numbers
- Imagine that you are a programmer hired to modify a payroll program
- You come across the following section of code:
double pay;
pay = hours * 7.5 + (hours / 40)
* (hours - 40) * 7.5 * 0.5;
The numbers are important to the program, but what do they mean?
Numbers like these are called "magic numbers"
They are magic because the value or presence is unexplainable without more knowledge
- Often, no one knows what they mean after 3 months, including the author
A programmer can often infer the meaning of numbers after reading the code carefully
Much better code is to use named constants rather than literal numbers
For example:
const double WAGE = 7.5;
const double OVERTIME_ADDER = 0.5;
const int HOURS_PER_WEEK = 40;
double pay;
pay = hours * WAGE + (hours / HOURS_PER_WEEK)
* (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
Now it is much easier to understand the code
- And see any problems or limitations
Programming Style: Constant Variables and Magic Numbers
- Since the meaning of literal ("magic") numbers is hard to remember, you should declare constants instead
const int FEET_PER_YARD = 3;
const double PI = 3.14159;
const double WAGE = 7.5;
const double OVERTIME_ADDER = 0.5;
const int HOURS_PER_WEEK = 40;
Note that the name is all uppercase letters with an underscore separator
This is a common coding convention that you must follow
^ top
3.1.3: Assignment Variations
- Unlike math, 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 is 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;
count++;
This is known as incrementing a variable
Similarly, you can decrement a variable
--count;
count--;
^ top
3.1.4: Arithmetic Precision and Range
- There are only a finite set of numbers in numerical data types
- This 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
You 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 numbers are too small they are set to 0.0
The Moral
- Integer and floating-point data types work well most of the time
- However, if you work with large positive or negative numbers, you must be sure you do not exceed the range of the data type
- Also, floating-point numbers have limited precision
- When math operations are performed repeatedly, they can become less precise
- You must be careful of precision when using floating-point numbers
^ top
3.1.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 you 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)
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
Example Application Using Casting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include <iostream>
using namespace std;
int main() {
double input;
cout << "Enter hours: ";
cin >> input;
int hours = (int) input; // prevents warning
int minutes = (int) ((input - (int) input) * 60);
cout << "In hours and minutes, this is "
<< hours << ":" << minutes << endl;
return 0;
}
|
^ top
3.1.6: Summary
- C++ has assignment variations of the form:
variable <op>= expression;
Not all numbers can be represented accurately by primitive C++ types
Integer values have a limited range
If your program assigns values too high or too low, integers wrap around
Floating-point numbers usually have enough range
However, they often suffer from lack of precision
cout.precision(17);
cout << .8F + .1F << endl;
cout << .8 + .1 << endl;
Type double has about twice the precision of type float
When floating point numbers get too large, they are set to inf
Similarly, when too small they are set to 0.0
C++ will automatically cast data of one type to another when necessary
However, you can explicitly cast values to a different type.
You must explicitly cast when C++ does not perform as you want.
Check Yourself
- How many ways can you add the integer 1 to a variable named index? List each way.
- What happens when you increase the value of an integer number beyond its range?
- How many digits that can be accurately stored in a float? double?
- Which is a valid typecast?
a(int)
int:a;
(int)a;
to(int, a);
- How do you truncate the decimal part of double variable?
^ top
Exercise 3.1
The following code does not display the correct value of degreesC.
#include <iostream>
using namespace std;
int main() {
double degreesC, degreesF;
degreesF = 122;
degreesC = 5 / 9 * (degreesF - 32);
cout << degreesC << endl;
return 0;
}
Specifications
- Save the code as
degrees.cpp
- Use a cast to correct the code and obtain the correct output.
- Submit your program along with your other exercises for this lesson.
^ top
3.2: Testing and Debugging
Objectives
At the end of the lesson the student will be able to:
- Describe the three kinds of programming errors
- Find the syntax errors in your programs
|
^ top
3.2.1: Kinds of Programming Errors
- There are three types of programming errors
- Syntax Errors
- Run-time Errors
- Logic Errors
Syntax Errors
- Violation of the "grammar" rules of the programming language
- For instance: forgetting a semicolon
- Syntax errors are discovered by the compiler
- You program will not compile if you have a syntax error
Errors Versus Warnings
- If you violate a syntax rule, the compiler gives you an error message
- Sometime the compiler will give you are warning message instead
- This indicates that your code is technically correct
- However, your code is unusual enough that it is probably a mistake
- Thus, you lose points for warning messages in your programming assignments
Run-time Errors
- Error conditions are sometimes detected by the computer at run-time
- For example: trying to divide by zero
- You program will usually end when it detects these errors
- How do you make sure your program does not have this type of error?
Logic Errors
- Errors in the program's algorithm
- For example: subtracting rather than adding in an arithmetic formula
- Computer does not recognize these types of errors
- Makes them the most difficult to diagnose
- How do you make sure your program does not have this type of error?
^ top
3.2.2: Anatomy of an Error Message
- To debug your programs you have to read the error messages
- As you read them you need to extract the important information
- For example, this error message tells you several important things:
fiddle.cpp: In function `int main()':
fiddle.cpp:6: error: parse error before `return'
- The name of the program
fiddle.cpp: In function `int main()':
- The function where the error occurs
fiddle.cpp: In function `int main()':
- The line number of the error
fiddle.cpp:6: error: parse error before `return'
- The error description
fiddle.cpp:6: error: parse error before `return'
- The most immediately useful information is the line number
^ top
3.2.3: How To Debug Syntax Errors
Repeat the following process until all the compiler errors are gone.
- Find the first error only.
You should look at the first error and ignore the rest. Often the first error causes all the rest of the errors. Reading any error beyond the first is often a waste of time.
- Analyze the first error.
Find the line reported by the first error. This is the line where the compiler first got confused. Look at this line in your code and try to spot the problem. The error message may provide clues as to the problem. If you cannot see a problem on that line, look for a problems on lines just before the reported line.
- If you cannot find the error in your code, then look at the causes of common errors in the next section.
Most times, you will spot the error. If you do not, then compare the first error message with those listed below. If you still cannot find your error, show it to the instructor. He will help you find and correct the problem. You can either bring it to him in person or email him.
- After correcting the first error, recompile your program.
^ top
3.2.4: Some Error Messages and Their Common Causes
Instructions
- If you cannot see an error in your code on or before the reported line number, then read the error message
- Compare the error description to the list below
- Click on the link and read the common causes
- Check your code for one of these common causes
Error Messages
More Information
^ top
3.2.5: Summary
- There are three kinds of programming errors
- Syntax errors
- Run-time Errors
- Logic Errors
- Sometimes the compiler will issue a warning if your code is unusual but still correct
- You should treat this warning as an error because it probably is a logic error
- Syntax errors are the easiest errors to find and correct
- I provide some instructions for finding and correcting these errors
- This information is summarized in How To Debug Compiler Errors
Check Yourself
- What are the three kinds of programming errors?
- What is the most useful information you can extract from an error message?
- What is the process for debugging syntax errors?
- What is the purpose of testing code that compiles without error?
^ top
Exercise 3.2
- Label this exercise: Exercise 3.2
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following and list the error messages you found and what you did to correct them in your exercise3.txt file.
Specifications
The following program was written by a person in a hurry. During the entry process a large number of errors were made. You need to find and correct the errors reported by the compiler by following the process described in section 3.2.3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* A very erroneous program.
*
* @author B. A. Ware
* @version 1.0 1/25/05
#include <iostrea m>
using namespace standard;
/**
* The main functoin for the program.
*/
int main() {
cout <<< "Hello out there.;
return;
}} / / end of main
|
^ top
3.3: Characters and Strings
Objectives
At the end of the lesson the student will be able to:
- Identify characters and strings from their literal representation
- Assign characters and strings to variables
- Perform arithmetic on characters
- Concatenate strings
- Collect characters and strings from user input
- Output characters and strings
|
^ top
3.3.1: Type char
- 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
Declaring and Assigning char Variables
- As with other data types, you must declare
char variables before use
char letter;
You assign values to a char variable using the equals sign
letter = 'A';
Just like numbers, you can combine declaration and assignment into one statement
char letter = 'A';
Also, you can declare multiple variables one one line:
char letter, letterA = 'A', letterB = 'B';
In addition, you can declare char constant values
const char AND = '&';
^ top
3.3.2: Using char
- Type
char is really an integer type
- This is because an ASCII code is stored in the same binary form as integers
- This allows the programmer to perform arithmetic on char values
- For example, you can add and subtract integer values to a char variable
char letter = 'A' + 2;
cout << letter << endl; // displays 'C'
What is the value of letter after the following code executes?
char letter = 'c' - 'a' + 'A'
User I/O with Type char
- Like numbers, you can output type
char using cout
char letter = 'A';
cout << letter << 'B' << endl;
Also, you can input type char using cin
cin >> letter;
cout << letter << endl;
Casting a char to an int
- Casting a
char value to int produces the ASCII code number
- For example, what would the following display?
char answer = 'y';
cout << answer;
cout << (int) answer;
Answer:
>y
>89
^ top
3.3.3: Introduction to Strings
- The
string class allows the programmer to use strings as a basic data type
- Defined in the string library and
std namespace
#include <string>
using namespace std;
Included automatically with our version of g++
Literal Strings
- A string is a sequence of characters
- String literals are made by enclosing a sequence of characters in double quotes
- For example:
"Hello" "b" "3.14159" "$3.95" "My name is Ed"
The double quotes used to mark the beginning and end of a string are not stored
Notice that the string "3.14159" could be expressed as a double by removing the quotes
However, a computer stores these two values very differently
double type 3.34159 is stored in eight bytes using the IEEE 754-1985 standard
String type "3.34159" is stored as ASCII characters
Both data types are useful for solving different problems
^ top
3.3.4: String Assignments
- You can assign literal strings to
string variables using the assignment operator
string s1 = "Hello Mom!";
cout << s1 << endl;
You can assign other string objects to a string object
string s1, s2;
s1 = "Hello Mom!";
s2 = s1;
cout << s2 << endl;
^ top
3.3.5: Joining Strings
- You can join two
string objects together using the '+' operator
- The join operation is called concatenation
string s1 = "Hello", s2 = "Mom!";
string s3 = s1 + s2;
cout << s3 << endl;
The string s3 now has the contents of both s1 and s2
You can also mix string variables and literal strings
string s1 = "Hello", s2 = "Mom!";
string s3 = s1 + " " + s2;
cout << s3 << endl;
The double quotes around the space is a literal string
Now our output looks better
^ top
3.3.6: String Output Using cout
- You can use the insertion operator << to output literals and variables of type
string
string s = "Hello Mom!";
cout << s << endl;
However, some characters are more difficult to output than others
For example, what would the compiler do with the following statement?
cout << "Say, "Hey!"" << endl;
Some characters cannot be output directly in a string
Also, the first 32 ASCII characters are not visible on our monitors
- Known as control codes because they control the output device
Even though these characters are not visible, we sometimes need to use them
- For example, a newline character
We need some way to "print" invisible and hard-to-print characters
Escape Sequences
- C++ can access some of the control codes and hard-to-print characters 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
3.3.7: String Input
Using cin
- You can use the extraction operator >> to input string data
string s1;
cout << "Enter something: ";
cin >> s1;
cout << "You entered: " << s1 << endl;
However, there are some complications
>> skips whitespace and stops on encountering more whitespace
Thus, you only get a single word for each input variable
If a user types in "Hello Mom!", you would only read "Hello" and not " Mom!"
This is because cin >> s1 works as follows:
- Skips whitespace
- Reads characters
- Stops reading when whitespace is found
Input Using getline()
- To read an entire line you can use function
getline()
- Syntax:
getline(cin, stringVariable);
For example:
string line;
cout << "Enter a line of input:\n";
getline(cin, line);
cout << line << "END OF OUTPUT\n";
Note that getline() stops reading when it encounters a '\n'
Using ignore()
- Recall that
cin >> s1:
- Skips whitespace
- Reads characters
- Stops reading when whitespace is found
- Thus
cin >> will leave a '\n' character in the input stream
- However,
getline() just stops reading when it finds '\n'
- This can lead to mysterious results in code like the following:
int n;
string line;
cout << "Enter your age: ";
cin >> n;
cout << "Enter your name: ";
getline(cin, line);
cout << "You entered: " << n << " " << line;
To get around this problem you can either:
- Only use
getline() before using cin (and never after using cin)
- Use
cin.ignore() after using cin and before using getline()
The "magic formula" for using cin.ignore():
cin.ignore(1000, '\n');
For example:
int n;
string line;
cout << "Enter your age: ";
cin >> n;
cin.ignore(1000, '\n');
cout << "Enter your name: ";
getline(cin, line);
cout << "You entered: " << n << " " << line;
Now you get the results you expect
^ top
3.3.8: Summary
- A character is a letter, number or special symbol
- You make character literals by enclosing a single character in single quotes
- You declare character variables using
char as the data type
char letter = 'A';
const char AND = '&';
Since char types are really integers, you can add and subtract them
char letter = 'A' + 2;
char letter2 = 'c' - 'a' + 'A'
You make string literals by enclosing characters in double quotes
You declare string variables using string as the data type
string s1 = "Hello Mom!";
To concatenate two strings, use the "+" operator
string s2 = s1 + " See yah!;
You use functions of the string object for some operations
Type string can be input and output with cin and cout
To read an entire line, you need to use the getline function
getline(cin, line);
Sometimes cin >> can leave a '\n' character in the input stream
To get around this problem you can either:
- Only use
getline() before using cin (and never after using cin)
- Use
cin.ignore() after using cin and before using getline()
cin.ignore(1000, '\n');
Check Yourself
- How are
char variables encoded?
- What type of delimiters are used to encapsulate single characters?
- Why can you perform arithmetic with
char values?
- What type of delimiters are used to encapsulate literal strings?
- What operator is used to join two strings?
- What is the escape sequence for a newline?
- How do you code a statement to read a string that includes spaces?
- What function do you use after using
cin and before using getline()?
^ top
Exercise 3.3
Write a program that prompt's the user for first and last names and then outputs the full name like that shown in the Sample Operation below.
Sample Operation
First name: Ed
Last name: Parrish
Full name: Ed Parrish
Specifications
- Start your text editor and save the following starter code as "
nameapp.cpp".
#include <iostream>
using namespace std;
int main() {
// Enter code here
return 0;
}
- Declare three string variables:
firstName, lastName, fullName
string firstName, lastName, fullName;
- Compile and execute the code.
If you encounter any syntax errors, correct them before continuing.
- Add code to get the user's first and last name using
cin.
Do not forget to prompt the user as shown in the sample operation above.
- Compile and execute the code.
If you encounter any syntax errors, correct them before continuing.
- Write a line of code to concatenate the first and last names and assign them to the variable
fullName
fullName = firstName + " " + lastName;
- Compile and execute the code.
If you encounter any syntax errors, correct them before continuing.
- Add code to your program to output the full name using
cout.
- Compile and execute the code, testing it to see if it operates like the Sample Operation shown above.
- Submit your "
nameapp.cpp" program as a separate file along with your exercise3.txt file.
^ top
3.4: Problem Solving and Pair Programming
Objectives
At the end of the lesson the student will be able to:
- Describe the steps for writing a program
- Discuss the pros and cons of pair programming
|
^ top
3.4.1: Solving the Problem
- Recall that programming is about solving problems using a computer program
- When you first start computer programming, you may think that the hard part is translating your ideas into code
- This is definitely not the case
- The most difficult part is finding a solution to the problem
- After finding a solution, translating your solution to code is a routine, almost mechanical, task
Problem Solving Phase
- Problem definition
- First step is to analyze and understand the problem
- Suggested first step in analysis is to state the problem in your own words
- In addition, you should ask questions about the problem to improve your understanding
- Algorithm design
- Next step is to define an algorithm
- Describe a set of steps that a computer can use to perform a task
- Algorithm (desktop) testing
- After developing an algorithm, you need to verify it is correct
- Develop a sample problem
- Walk through each step mentally or manually
- If there is an error, change the algorithm
^ top
3.4.2: Writing the Program
- After you are sure the algorithm works, then write the program code
- If your algorithm is correct, this phase is usually easy
Implementation Phase
- Translate the algorithm to C++ code
- Start with a simple program that you know works (see template below)
- Add your algorithm to the code one step at a time
- Compile and run you program after you add each step
- If you find an error, correct it before continuing
- Testing
- After code compiles and runs, you test it
- When you test, make sure the program:
- Does what it is supposed to do
- Does not do what it is not supposed to do
- Does what it used to do
- Working program
- When it works well, you document and deliver the program
Starting Template
#include <iostream>
using namespace std;
int main() {
// Enter code here
return 0;
}
^ top
3.4.3: Pair Programming
- Defining problems and developing algorithms on your own is often difficult
- Also, when you translate the algorithm into code, you often run into syntax errors that are difficult to see
- It would be nice to get help from another human in these cases
- However, the instructor prohibits asking most people from looking at your code
- What is the solution to this problem?
- Answer: Pair Programming for Homework Assignments
Defining Pair Programming
- Pair programming is two people work together on one computer at the same time
- Exactly two people: not one nor three or more
- Exactly one computer: not two or more
- The driver operates the keyboard and mouse
- The navigator actively participates in the programming
- Analyzes the design and code to prevent errors
- Also in charge of using printed reference materials like textbooks
- Each person "drives" about half the time
- Physically get up and move positions when switching roles
- At most 25% of your time is spent working alone
- Any work done alone is reviewed by the other person
- The objective is to work together and to learn from each other
- You cannot divide the work into two pieces with each partner working on a separate piece
Why Pair Program?
- Students who pair program report:
- Higher confidence in a program solution
- More satisfaction with programming
- Instructors report higher retention rates
More Information
^ top
3.4.4: Best Practices
- You may choose any other student in this class for a partner
- Both of your names appear on the assignment
- When choosing partners and working together, certain practices help you perform better
- Pair-programmers are more successful when they have similar experience levels
- Need to find a partner with whom you can easily exchange ideas
Getting Along
More Information
^ top
3.4.5: Summary
- Programming is about solving problems using a computer program
- To develop a computer program, you start by defining the problem(s) to solve
- Once a problem is well defined, you develop an algorithm to solve it
- Once the algorithm is define, then you write the program
- After the program compiles and runs, you test it to verify it works correctly
- Once the program works, you finish documenting it and then submit the code
- Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
- Use some care when choosing a pair-programming partner to maximize your success
- In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten
Check Yourself
- Why is pair programming helpful?
- What are the rules of pair programming?
^ top
Exercise 3.4
- Label this exercise: Exercise 3.4
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in your exercise3.txt file.
Specifications
- We will count off and divide into separate groups
- Within your group, exchange email addresses so that you can send the answer to this exercise to each other.
- As a group, define the problem and describe an algorithm for converting weight measurements from pounds to grams.
- Describe the algorithm in your
exercise3.txt file
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: October 13 2005 @15:15:13
|