chap2_mine.doc 2-1
Miscellaneous technical stuff (Chap 2)
double, float, and char data types; printing messages, arithmeticprecedence rules, if statement, relational operators, compound assignment operators, standard library of functions
branching, creating readable output, errors, debugging
I’m really sorry that I will bore you. There is very little thinking in this chapter.
Branching is the only slightly interesting concept.
New Data Type: double
S’pose you want to store the price of an object in dollars and centsin a variable price. pricecannot have data type int. To allow for the decimal places, we will declare price to have data type double. This data type allows the variable to hold a real number, one that may contain decimal places.
double price;
price = 3.50;
cout < price; || 3.5
Notes:
- C++prints only the decimal places necessary to represent the value of the number accurately. In Chapter 3, we’ll see how to specify the number of decimal places to print.
- Float was the original. Hardly used anymore. You’ll see it in your workbook. Use double. It’s double the size of float.
- Division gives decimal: cout < 7.0/2; || 3.5
Making Decisions Using a Conditional or if Statement
Until now, our programs have executed each statement in order. A conditional or if statement allows a program to branch, which means to allow the path of execution to go in one of two directions, depending on a specific condition. Some statements will be executed, and others will not, depending on the condition's value. The computer will decide after evaluating the condition.
In a conditional statement, the keyword if is followed by some condition (in parentheses) that evaluates to either true or false. Same as the cond’n in for loop. Details later.
•If the condition is true, we execute the statement that follows and continue processing.
int age = 23;
if (age >= 18)
cout < " Vote";
cout < endl;
•If the condition is false, we simply skip that statement and "fall through" to the next instruction.
int age = 13;
if (age >= 18)
cout < " Vote";
cout < endl;
Ifageis greater than or equal to 18, we print the word "Vote,";if not, we don't. Instead, we proceed to the next statement, which sends the cursor to a new line in all cases.
General Form of an if Statement
if (cond) Warning:no semicolon here
stmt-1; body of if statement
stmt-2; next statement
The keyword if is followed by a condition (cond), in parentheses. cond is evaluated; if it is true, we execute stmt-1; if cond is false, we skip stmt-1. In either case, we continue with stmt-2, which follows the if statement.
Three rules:
- If true, execute.
- If false, ignore.
- If more than one statement in the body, enclose the block of statements in curly braces, {}.
Like the for loop, put the open brace at the end of the header and the close brace under the ‘i’.
if (cond){
stmt-a;
stmt-b;
}
stmt-2;
e.g.: count the voters.
int age=16,//age =19
voters=0;
if (age>=18){
cout < “Vote ”;
voters++;
cout < voters < “ voters” < endl;
What if (I’m allowed) I forgot the braces?
Notes:
- If you put a semicolon after theif condition, the if statement terminates at that point. The condition is tested, but nothing happens, and the following statement (stmt-1) is executed in all. (Show on board.)
- It is good style to put the if condition on one line and the body on the next line, indented one tab position.
if (cond){
stmt-a;
stmt-b;
}
stmt-2;
e.g.: count the voters.
Precedence: The Order of Operations
How much is 2+3*4?
Multiplication comes before addition (as in PEMDAS).
There are two uses for the minus sign, subtraction and negation (unary minus because it has one operand). Similarly, for the plus sign. Unary operators have precedence over binary operators.
What is the value of 6*-4 ? -24. The 4 is negated, then multiplied by 6.
Associativity determines which has priority if two operators have the same precedence.
• For the binary operators (*, /, %, +, and -), associativity is left to right.
•For the unary operators (unary minus, unary plus, ++, and --), associativity is right to left.Don’t sweat this.
How much is 24/4*3? Divide first to get 18.
How much is 5 - 3 + 2 * 6 / 2 ? 8
Notes: Use ()
- to override precedence. Writey = a / (b + 3) to add before dividing.
- to make a formula clearer.
- if you aren’t sure of the precedence.
Make a Table?
Variable versus string
int help = 3;
cout < help;
cout < "help";
Assignment 2 is due 2 classes from today.(?Show them “Sums” chap 3 pg 5 of my notes.)
NICER OUTPUT
- Print a Heading on the Output
cout < "Table of Expenses" < endl;
- Print Messages Together with Valuesso the reader knows what the value means.
Note that we usually include blanks in messages to separate the words from the surrounding values.
- Ending the Program
After printing the output, we could just end the program. But its better style to first print a message like:
cout < "The table is finished" < endl;
This message, called a trailer message, is helpful to both the programmer and the user. It signals to the programmer that the program has run to completion and has not become stuck in the middle. To the user, it signals that the output is finished, and no pages are missing.
Notes:
- A comment is associated with the listing of the program, while a heading, labeled output and a trailer message are associated with the output. Both are for the benefit of humans. Which ones?
- If the output is generated by a loop, where would the cout < “heading”and cout “done” statements go?
- Double-Spacing and its Variants
endl makes the cursor go to the beginning of a new line. It is possible to double space (or skip a line) by using two endl's or stay on the same line after printing by omitting endl. An endl can be printed at the beginning of a line, in the middle or at the end.
- Column Headings
Instead of having messages and values printed across the page, we make a neat table with column headings. Column headings should be printed once--before the loop starts but after the table heading. Show them.
The Tab Character
The tab character, '\t', consists of two keystrokes, a backslash followed by a 't'. Printing '\t' causes the cursor to move to the next tab position before printing. This feature is very useful for aligning output in columns. It can stand alone or be part of a string.Sometimes we need more than one tab to align the values under the headings.
What is printed by the following?
cout < "One\tTwo\t\tTre" < endl < "For";
OneTwoTre
For
------
Story: At University A, sections of a certain class fill very quickly because of the popularity of Professor B. To determine if a student can enter a closed section, the registrar uses the student's grade point average (which we will call gpa) to evaluate a complicated mathematical formula, which we will callresult = formula(gpa). If the value of the formula is positive, the student gets into the section. The registrar has asked youto construct a chart showing various values for the grade point average and the formula. This way, when a student comes in, the registrar can simply look up the average in the table and find the correct answer to the formula instead of recomputing it each time.
It is customary and helpful when writing pseudocode to indent as you would in a program. Then it is clear how the parts of the pseudocode go together in the translation.
headings
for values of gpa from 0.00 to 4.00, increasing by 0.50
compute result = formula ( gpa )
print gpa,result
ifresult is positive
print "Admit"
end of table message
See formula.cpp
------
Escape Sequences
The symbol \ is called the escape character and tells the computer to treat the next character as special. We call a backslash and a character togetheran escape sequence. We can use the escape character to tell the computer to print characters which otherwise would be unprintable, like " and \ itself (elaborate). \n is the newline character. It works like endl.
They can go anywhere in a string literal. See your text for the rest.
What would the following print? Check your answer in LAB?
cout < "t\t\\ \" \nn";
t\ “
n
You try one :
cout <“\n\”\\n\is newline.”;
On a new line “\n is newline.
Relational Operators
A number of operators can be used to test the relationship between values; they are called relational operators. They are often used in conditions (e.g. if, for).
less thana < b
greater thannum > 4
<=less than or equal tox + 1 <= 12
>=greater than or equal toresult * 3 >= 3.5 - w
==equal to (logical equals)sqnumber == 16
!=not equal toanswer != 7
Notes:
- The logical equals operator, ==, is not the same as the = used in mathematics to compare two values. C++ uses the = symbol for assignment, but it uses == for comparison. Frequent error.
- The != operator is also different from the symbol used in mathematics (). In C++,! stands for "not," so != is "not equal."
- Each operator is two keystrokes with no space between them. May leave a space b4&after.
Compound Assignment Operators: +=, -=, *=, /=, %=
Shorthand –see my notes.
Reminder: USE ++ only as stand alone for now.
Since we can also use the += operator to increment by 1, we have four equivalent statements:
number = number + 1;is equivalent to
number += 1;is equivalent to
number++;is equivalent to
++number;
Experienced C++ programmers usually use number++ (unless they need ++number).
Precedence of Arithmetic, Assignment, and Relational Operators
------
Associativity
highest precedence - (unary) + (unary) ++ --right to left
(done first)
* / %left to right
+ -left to right
< <= > >=left to right
== !=left to right
lowest precedence = += -= *= /= %=right to left
(done last)
Assignment operators have lowest precedence and associate right to left. Must fully evaluate the expression on the right before assigning it to the variable on the left.
Parentheses have highest precedence. They can be used to override the rules and change the order in which operations are executed.
------
Read about Scientific Notation. I won’t test it.
STANDARD LIBRARY OF FUNCTIONS (sec 2-5)
C++ provides many mathematical functions in its library. To use Standard Library of Math Functions , must# include <cmath
int i;
double r;
sqrt()r=sqrt(64) ; // r is 8
abs() i = abs(-25); // i is 25
fabs() r = fabs(-2.72); // r is 2.72
ceil() i = ceil(3.24); // iis4
floor() i = floor(3.84); // iis 3
(Note: same as i = 3.84 for positive values. Behavior for negative numbers is implementation dependent)
How would you round to the nearest number?
i = r + 0.5;for positive numbers. Use floor() for negative values.
The library contains trigonometric functions such as sin(), cos(), and tan().Theangle is measured in radians.
Notes
- Each #include directive must appear on its own line with nothing else on the line.
- Abs() doesn’t require cmath
The exit() function (chap 6 in text)
Another useful function (which does not need a header file to be included these days) is exit(). When it is encountered, the program terminates.
exit(0); indicates normal termination.
exit(1); (or more) indicates abnormal termination.
Does this remind you of return()?
Data Type char
C++ has another simple data type. It is char, which stands for character. A variable of this data type can hold any one character (e.g., 'a' or ' ' or '?'). A character is essentially anything that can be typed--a number, letter, space, period, or symbol. Note that values of type char are enclosed in single quotation marks, while stringliterals are enclosed in double quotation marks. (The single quote is under double quote on the keyboard—not next to the one.)In addition, special characters like the tab character '\t' and the newline character '\n' (which can be used in place of endl) are values of type char. The Appendix contains a list of all the printable characters that can be used in C++. It also shows the associated integer value for each char value, called its ASCII value. The ASCII values for characters range from 0 to 255. Each character is stored internally as an integer.
char letter;
letter = 'a';
if (letter != 'b')
cout < "letter has the value " < letter < '\n';
Output? Since letter is not equal to 'b', this example prints the following:
letter has the value a
DEBUGGING
An error in a program is often called a "bug." Debugging is the process of finding and removing errors from a program without creating new ones. Since a program rarely works perfectly the first time it is run, debugging is an important programming skill. There are various types of errors that a program might have.
Compilation Errors
A compilation error is one caught by the compiler while it is translating your program into machine language before running it. Compilation errors caused by mistakes in the syntax or form of a statement are called syntax errors.
fir(i = 1; i< 5; i++) misspelled keyword
a = (b + 1/3; missing right parenthesis
x + 3 = 5; expression on the left of an assignment statement
x = 5 missing semicolon—common error
x=8/;missing second operand (have I defined?)
The compiler may also generate warnings, which are normally less serious than errors. Some (but not all) warnings can be ignored, but this is not a good habit. Look and think.
Errors caught in the second phase of compilation are linker errors. It can’t fetch the code from the library.
Execution Errors
An execution error is detected once the program is running, which is why it is sometimes called a run-time error.
int x = 3, y = 0;
x = x / y;
Logic Errors
Alogic error, is the hardest to catch because there may be no error messages. The program may run but the answers are wrong. A logic error may be something simple--for example, initializing a variable to 1 instead of 0, or multiplying by 2 instead of 3, or using an incorrect formula--but it can also be a basic mistake in the logic of the program. The programmer has to catch logic errors by tracing, handchecking and testing the program on all possible sets of data. Sometimes adding cout statements helps you see what’s happening. (Example) You are welcome to learn how to use the debugger.
Be aware, too, that many statements that look like compilation errors are actually valid C++ statements. For example, the statement shown below is not a compilation error, although someone probably used the wrong symbol for assignment:
x == x + 3;
Unfortunately, this is a valid statement in C++, even though it will not assign a value to x.
More examples:
net=gross+tax; product=a/b;
The computer has no problem following the instructions, but it gives the wrong results.
If a program is written correctly, there is no need to debug it. Be extremely careful in planning your original solution to the problem, writing the program, and hand simulating it before you run it. If this is done, and the rules for good style are followed, most mistakes will be caught before they do any damage. Time spent planning your program is saved many times over.
LAB: Errors.doc (copied from below)
Exercise 24 gives you practice in finding errors of all three types.
24. The following program has many bugs in it. Try to find them and identify the type (compilation, execution, or logic) of each error.
// do various calculations, including
/ finding the perimeter of a rectangle
include iostreem;
ussing name standard;
void mane{}
integer x;
y: double;
int perimeter;length;width;
{
x == 4.0;
y = .5 * 3 \ (x - 4);
if x = 5
cout < 'five'
2y = x + (5 + 4 % 3;
perimeter = length + width * 2;
cout perimeter,length,width" endl)
};
// do various calculations, including
// finding the perimeter of a rectangle
#include iostream
using namespacestd;
int main()
{int x;
double y;
int perimeter, length = 3, width = 5;
//{
x = 4.0;//warning
y = .5 * 3 / (x - 4);
if (x ==5)
cout < "five";
y = x + (5 + 4 % 3);
perimeter = (length + width) * 2;
cout perimeter < " " < length < " " < width < endl;
system("pause");
}