What We Will Cover
Continuations
Homework Questions?
Viewing WebCT Assignment and Exercise Results
Homework Discussion Questions (Thursday)
- What is the C++ code for:
a + b - c
- What is the C++ code for:

- What is the C++ code for:
(a - b)2
- What is the C++ code for:

- What is the C++ code for:

- When might truncation in integer division be useful?
- What math equations can NOT be implemented in C++?
- What improvements can you suggest to the C++ language to make it easier to write math equations?
^ top
3.1: Interactive Input
Learner Outcomes
At the end of the lesson the student will be able to:
- Generate code to display program output to the console
- Format numbers during output
- Generate code to get user input from the console
- Prompt users when requesting input
|
^ top
3.1.1: About Interactive Input
- For programs used infrequently, you can easily put data directly in the code
- For instance, to calculate the average of four numbers:
1
2
3
4
5
6
7
8
9
|
#include <iostream>
using namespace std;
int main() {
double average = (32.6 + 55.2 + 67.9 + 48.6) / 4;
cout << "Average = " << average << endl;
return 0;
}
|
- However, you must recompile the program if you change any number
- It is more convenient for users to enter data rather than changing the code and recompiling a program
- This section discusses how you can display user output to the console
- Also, it discusses how you can get user input while a program is running
^ top
3.1.2: Using cin
- To get data from a user, we use
cin
cin >> num;
cin is an input stream object bringing data from the keyboard
'>>' (extraction operator) points toward where the data goes
Waits on-screen for keyboard entry
Value entered at keyboard is 'assigned' to num
You can input more than one variable in a cin statement
cin >> v1 >> v2 >> v3;
You cannot use a literal number in a cin statement
You must input data into a variable
^ top
3.1.3: Prompting Users
- Good programming practice is to always "prompt" users for input
int numOfDragons;
cout << "Enter number of dragons: ";
cin >> numOfDragons;
Note that you do not put a newline at the end of the prompt
The prompt waits on the same line for keyboard input as follows:
Enter number of dragons: _
Where the underscore above denotes where keyboard entry is made
Every cin should have a cout prompt before it
In addition, often a good idea to echo what the user typed
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
using namespace std;
int main() {
double num1, num2;
cout << "First number: ";
cin >> num1;
cout << "Second number: ";
cin >> num2;
cout << num1 << " + " << num2 << " = "
<< num1 + num2 << endl;
return 0;
}
|
Maximizes user-friendly input/output
^ top
3.1.4: Output Using cout
cout sends data to the console
- Technically,
cout is known as an output stream
- An output stream gets data from some source and sends it to a destination
- Like a stream that moves water from one place to another
- The insertion operator "
<<" inserts data into the cout stream
- Any data can be output to the display screen
- Variables
- Literals
- Expressions (which can include all of above)
int numberOfGames = 12;
cout << numberOfGames << " games played." << endl;
3 values are output:
- Value of the variable
numberOfGames
- Literal string "
games played."
- A newline character
Note that you can have multiple values in one cout
^ top
3.1.5: Newlines in Output
- Recall that '
\n' is an escape sequence for the char "newline"
- A second method is to use the object
endl
- Examples:
cout << "Hello World!\n";
Sends string "Hello World!" followed by a newline
cout << "Hello World!" << endl;
Same result as above
^ top
3.1.6: Decimal Formatting
- Numbers may not display as you'd expect!
double price = 78.50;
cout << "The price is $" << price << endl;
If price (declared double) has value 78.5, you might get:
The price is $78.5
We must explicitly tell C++ how to output numbers in our programs!
"Magic Formula" to force decimal sizes:
cout.setf(ios::fixed); // fixed notation, not scientific
cout.setf(ios::showpoint); // show decimal point
cout.precision(2); // show 2 decimal places
Now all future values have exactly two digits after the decimal place
For example:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
double price = 78.5;
cout << "The price is $" << price << endl;
Now results in the following:
The price is $78.50
If you want to reset a flag, use cout.unsetf()
For example:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
We will cover output formatting in more detail in a few weeks
^ top
3.1.7: Summary
cin is an input stream bringing data from the keyboard
- '
>>' (extraction operator) points toward where the data goes
- When designing I/O:
- Prompt the user for input
- Echo the input by displaying what was input
cout is an output stream sending data to the monitor
- The insertion operator "
<<" inserts data into cout
- There are two ways to output a newline character:
cout << "Hello World!\n";
cout << "Hello World!" << endl;
cout includes special tools to specify the output of type double
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
Allows you to display numbers with 2 decimal places
Check Yourself
- Why do programs need interactive input?
- Why is it a good practice to prompt users before input?
- What is the escape sequence for a newline?
- What is the "magic formula" for outputting numbers with two decimal places?
^ top
Exercise 3.1
The following code gets a number from the user.
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <iostream>
using namespace std;
int main() {
double num;
cout << "Enter a number: ";
cin >> num;
// Put your code here
return 0;
}
|
Specifications
- Save the following code as
format.cpp
- Modify the code to display the number a user enters in both currency and percent formats, like this:
Enter a number: 12.3
As a dollar amount: $12.30
As a percent: 12.3%
Note that you will need to have two cout.precision() statements in your code.
- Submit your program source code (
format.cpp) as the solution to this exercise.
^ top
3.2: Testing and Debugging
Learner Outcomes
At the end of the lesson the student will be able to:
- Use TextPad to compile and run programs
- Describe the three kinds of programming errors
- Find the syntax errors in your programs
|
^ top
3.2.1: Compiling and Running a Program Using TextPad
- Many text editors have provision for compiling within the editor
- We use TextPad in our class room as a text editor
- Note that you can install TextPad at home
- To make your in-class exercises easier, we have set up TextPad to compile and run C++ programs
- We will use the following program for demonstration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/**
* hello.cpp
* Purpose: Prints a message to the screen.
*
* @author Ed Parrish
* @version 1.0 8/30/05
*/
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
} // end of main function
|
Compiling with TextPad
- Load your source code into the active TextPad window
- Select the Tools menu
- Select Compile C++
- If there are any syntax errors, you will see a page showing them
- Otherwise, you will return to your source code page
Running Programs with TextPad
- Load your source code into the active TextPad window
- Select the Tools menu
- Select Run C++ Application
- Your program will run in a console window
^ top
3.2.2: Kinds of Programming Errors
- There are three types of programming errors
- Syntax Errors
- Run-time Errors
- Logic Errors
Syntax Errors
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
- For example:
erroneous.cpp:10:1: warning: "/*" within comment
This indicates that your code is technically correct
However, the code is unusual enough that it may be a mistake or is otherwise undesirable
Thus, you lose points for warning messages in your programming assignments
Run-time Errors
Logic Errors
^ top
3.2.3: 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.4: How To Debug Syntax Errors
Repeat the following process until all the compiler errors are gone.
- Find the first error (or warning) only.
You should look at the first error or warning and ignore the rest. Often the first error or warning causes all the rest of the errors and warnings. Reading any error or warning beyond the first is often a waste of time.
- Analyze the first error.
Find the line reported by the first error or warning. This is the line where the compiler first got confused or spotted a potential problem. 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 or warning, recompile your program.
^ top
3.2.5: 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.6: Summary
- To make your testing and debugging easier, we have set up TextPad to compile and run C++ programs
- 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
In this exercise we practice debugging syntax errors.
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.
- Save the following code as
erroneous.cpp
- Find and correct the errors reported by the compiler by following the process described in section 3.2.4
- Submit your corrected program source code as the solution to this exercise.
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: Problem Solving and Pair Programming
Learner Outcomes
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.3.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.3.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
1
2
3
4
5
6
7
8
|
#include <iostream>
using namespace std;
int main() {
// Enter code here
return 0;
}
|
^ top
3.3.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.3.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.3.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?
- Why should you change who is driving when you pair-program?
- What is the role of the person who is not using the keyboard?
- Why do the rules of pair-programming require you to use only one computer at a time to edit and compile code?
^ top
Exercise 3.3
In this exercise we see who might be a compatible pair-programming partner for the next homework assignment.
Specifications
- We will count off and divide into separate groups
- Within your group, exchange names and write down everyone's name.
- Next to the name, write the amount of programming knowledge and experience for that student. I suggest the following scale:
- Absolute beginner
- Some programming knowledge
- Can program in another programming language
- Can program in C++
- Save all the information you collect in a file named
students.txt.
- Submit the
students.txt file as the solution to this exercise.
Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student must submit the same students.txt file.
^ top
3.4: Characters and Strings
Learner Outcomes
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.4.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
You can see this relationship in an ASCII Table
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 line:
char letter, letterA = 'A', letterB = 'B';
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;
^ top
3.4.2: Introduction to Strings
- A string is a series of characters
- 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
- 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.44159 is stored in eight bytes using the IEEE 754-1985 standard
String type "3.44159" is stored as ASCII characters
Both data types are useful for solving different problems
^ top
3.4.3: 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.4.4: 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.4.5: 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.4.6: 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 non-whitespace 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.4.7: 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 = '&';
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!;
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?
- 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.4
In this exercise we 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. Note that the first two lines of the Sample Operation are the input (with prompts) and the last line is the output of the program.
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".
1
2
3
4
5
6
7
8
|
#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 the solution to this exercise.
^ top
Wrap Up
Reminders
Due Next: A2: Arithmetic Formulas (2/22/07)
Exercise 2 and CodeLab Lesson 2 (2/22/07)
A3: Conversions (3/1/07)
Exercise 3 and CodeLab Lesson 3 (3/1/07)
- When class is over, please shut down your computer
- You may complete unfinished exercises at the end of the class or at any time before the next class.
^ top
Home
| Blackboard
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: February 15 2007 @15:14:04
|