Unit 2 PowerPoint Slides

advertisement
EGR 2261 Unit 2
Basic Elements of C++



Read Malik, Chapter 2.
Homework #2 and Lab #2 due next
week.
Quiz next week.
A Quick Look at a C++ Program
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
2
A Quick Look at a C++ Program
(cont’d.)
• Sample run:
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
3
A Quick Look at a C++ Program
(cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
4
A Quick Look at a C++
Program(cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
5
A Quick Look at a C++ Program
(cont’d.)
• Variable: a memory location whose contents can be
changed.
?
?
?
?
Figure 2-2 Memory allocation after the four variable declaration statements
?
?
?
Figure 2-3 Memory spaces after executing the statement length = 6.0;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
6
The Basics of a C++ Program
• Programming language: a set of syntax rules, semantic
rules, special symbols, and reserved words.
• Syntax rules: rules that specify which statements
(instructions) are legal or valid.
• Semantic rules: determine the meaning of the
instructions.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
7
Special Symbols
• List of special symbols in C++ :
– From page 7 of Ray Lischner’s C++ in a Nutshell. (O’Reilly, 2003).
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
8
Reserved Words (Keywords)
• Reserved words (or keywords):
– You cannot redefine these words.
– You cannot use them for anything other than their
intended use.
Examples:
– int
– using
– return
– See Appendix A (next slide) in textbook for
complete list.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
9
Tokens
• Tokens: the smallest meaningful units of a program.
• C++ tokens include special symbols, reserved words,
and identifiers.
Reserved words
Identifier
Special symbol
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
11
Identifiers
• An identifier is the name of something in a program.
– Identifiers can contain letters, digits, and the underscore
character (_), but no other characters or symbols.
– Identifiers must begin with a letter or underscore (not a
digit).
• C++ is case sensitive.
– For example, number, Number, and NUMBER are three
different identifiers.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
12
Identifiers (cont’d.)
• Examples of legal identifiers in C++:
• first
• payRate2
• Employee_Salary
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
13
Comments
• Comments are for the reader, not the compiler.
• Two types:
– Single line: begin with //
// This is a C++ program.
// Welcome to C++ Programming.
– Multiple line: enclosed between /* and */
/*
You can include comments that can
occupy several lines.
*/
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
14
Whitespace
• Every C++ program contains whitespace.
– Includes blanks, tabs, and newline characters.
• Whitespace must separate reserved words
and identifiers from each other.
• Proper use of whitespace (such as indenting)
also makes programs more readable.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
15
Data Types
• Data type: set of values together with a
set of allowed operations on those values.
• C++ data types fall into three categories:
– Simple data types
– Structured data types
– Pointers
• For the next few weeks we’ll mostly use
simple data types.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
16
Simple Data Types
• Three categories of simple data:
– Integral: integers (numbers without a decimal).
• Can be further categorized:
– char, short, int, long, long long,
bool, unsigned char, unsigned
short, unsigned int, unsigned long
– Floating-point: decimal numbers.
• Can be further categorized:
– float, double, long double
– Enumeration type: user-defined data type.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
17
Partial Hierarchy of Data Types
Data Types
Integral
(int, bool,
char, …)
Simple Data
Types
Structured
Data Types
Floating-Point
(float,
double, …)
Enumeration
Pointers
Simple Data Types (cont’d.)
• The ranges shown above are typical. Different
compilers may allow different ranges of values.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
19
int Data Type
• Examples of int data:
-6728
0
78
+763
• Do not use commas within numbers. Typing 1,430
instead of 1430 will usually cause an error.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
20
bool Data Type
• The bool type has only two possible values: true
and false.
– It’s useful for keeping track of true/false (Boolean)
information, such as whether a person’s age is
greater than 21.
• This is considered an integral data type
because it’s actually implemented as a 0 for
false and a 1 for true.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
21
char Data Type
• Used for single characters: letters, digits, and
symbols.
• Each character is enclosed in single quotes:
– 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character.
– Written ' ', with a space left between the single quotes.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
22
char Data Type (cont’d.)
• Different character sets exist, but we’ll use ASCII.
• ASCII: American Standard Code for Information
Interchange
– Each of 128 integer values (from 0 to 127) represents a
different character; see Appendix C in textbook (next
slide).
– Collating sequence: Characters have a predefined ordering
based on the ASCII numeric value.
For example, the ASCII code for 'A' is 65 and the ASCII
code for ‘D' is 68, so we can say that 'A' < ‘D'.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
23
Floating-Point Data Types
• Non-integer numbers can be entered or displayed
using decimal notation or using a modified scientific
notation.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
25
Floating-Point Data Types (cont’d.)
• float
– Typical Range: -3.4E+38 to 3.4E+38 (four bytes)
• double
– Typical Range: -1.7E+308 to 1.7E+308 (eight bytes)
• Ranges of data types are system-dependent.
• We’ll generally use double when we want a
floating-point number.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
26
Review: Simple Data Types
• Three categories of simple data:
– Integral: integers (numbers without a decimal)
• Can be further categorized:
– char, short, int, long, long long,
bool, unsigned char, unsigned
short, unsigned int, unsigned long
– Floating-point: decimal numbers
• Can be further categorized:
– float, double, long double
– Enumeration type: user-defined data type.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
27
Arithmetic Operators
• Some C++ arithmetic operators:
•
•
•
•
•
+ addition
- subtraction
* multiplication
/ division
% modulus (or remainder)
• You can use +, -, *, and / with integral and floatingpoint data types.
• You can use % only with integral data types.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
28
Arithmetic Expressions
• Arithmetic expressions combine values (operands)
and arithmetic operators to yield a result.
• Example: 12.8 * 17.5 - 34.50
• Arithmetic expressions can be:
– Integral expressions: all operands are integers.
– Floating-point expressions: all operands are floating-point.
– Mixed expressions: some operands are integer, some are
floating-point.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
29
Integral Expressions
• An integral expression is an arithmetic expression in
which all operands are integers.
– Yields an integer result.
– Example: 2 + 3 * 5
– Caution: When you use / with integers, the integer
result is truncated (no rounding).
– Example: 7 / 2 yields a result of 3
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
30
Quotient and Remainder
•We know that 7 ÷ 2 = 3.5
•Recall that another way of looking at it is to say that
7 ÷ 2 is equal to 3 with a remainder of 1.
•In this example, 3 is called the quotient and 1 is called
the remainder.
•In C++, using the / operator with integers yields the
quotient.
•Example: In C++, 7 / 2 yields a result of 3
•And using the % operator with integers yields the
remainder.
•Example: In C++, 7 % 2 yields a result of 1
Floating-Point Expressions
• A floating-point expression is an arithmetic
expression in which all operands are floating-point.
– Yields a floating-point result.
– Example: 7.0 / 2.0
• The expression above yields 3.5
– Another example: 12.8 * 17.5 - 34.50
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
32
Operator Precedence and
Associativity
• Operators inside parentheses are evaluated first.
• *, /, and % have the same level of precedence and
are evaluated next.
• + and – have the same level of precedence and are
evaluated next.
• Arithmetic operators on the same level of
precedence are performed from left to right. (They
have “left-to-right associativity.”)
• Example: Evaluate the following expression:
3 * 7 - 6 + 2 * 5 / 4 + 6
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
33
Mixed Expressions
• A mixed expression is an arithmetic expression that
has some integer operands and some floating-point
operands.
• Examples:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 - (3.6 + 5) / 2
• See next slide for rules on how C++ evaluates these.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
34
Mixed Expressions (cont’d.)
• Evaluation rules:
– The precedence and associativity rules from above
still apply.
– If an operator has the same types of operands:
• It is evaluated according to the type of the operands.
– If an operator has both types of operands:
• Integer is “promoted” to floating-point.
• Operator is evaluated.
• Result is floating-point.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
35
Type Conversion and Casting
• Implicit type conversion (also called coercion) occurs
when C++ automatically changes a value of one type
to another type. We’ve seen an example of this with
mixed expressions.
• C++ also lets you perform explicit type conversion
using the cast operator:
static_cast<dataTypeName>(expression)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
36
Type Conversion (Casting) (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
37
Truncating Versus Rounding
•Note that when C++ converts a floating-point
number to an integer, it truncates rather than
rounds.
•Example: static_cast<int>(7.01) and
static_cast<int>(7.99) both give 7.
•Often we want to round to the nearest integer. At
several points (such as on p. 159) the book uses a
standard trick to do this: add 0.5 to your floatingpoint number before you convert it to integer.
•Example: static_cast<int>(7.01 + 0.5)
gives 7 but static_cast<int>(7.99 + 0.5 )
gives 8.
Unary Versus Binary Operators
• The arithmetic operators we’ve discussed are all
binary operators: they take two operands.
• Some operators are unary operators (one operand).
• In fact, + and – can be either binary or unary,
depending on the context.
• Unary – is negation.
• Example: –2 * 3
• Another example: +2 * –3
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
39
Other Operators
• As well as the arithmetic operators discussed above,
C++ has many other operators.
• See Appendix B (next slide) in the textbook for a
complete list that shows precedence and
associativity of all the operators.
– Note from this list that unary + and – have higher
precedence than binary + and – .
• Unfortunately the table in Appendix B contains a few
typos, so be sure to fix them using the list of
textbook typos on the course website.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
40
Review: Data Types
• Recall that C++ data types fall into three
categories:
– Simple data types (int, char, bool, double, …)
– Structured data types
– Pointers
• For the next few weeks we’ll mostly use
simple data types, plus one structured data
type called the string type.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
42
string Type
• A string is a sequence of zero or more characters
enclosed in double quotation marks.
– Contrast with char data type, which is a single character
inside single quotation marks.
• Unlike the simple data types discussed earlier, the
string data type is not built into the core C++
language. It’s a programmer-defined type supplied in
the C++ Standard Library. So a program that uses
strings must have the following line:
#include <string>
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
43
Variables
• The expressions we’ve looked at above used constant
numeric values.
– Example: 2 * 3.5
• In most programs you’ll also use variables, which are
named memory locations whose values can change
as the program runs.
– Example: 2 * payRate
• When naming your variables, be sure to follow the
rules listed earlier for identifiers.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
44
Declaring Variables
• In C++ you must declare each variable’s data type
before you can use the variable.
• Syntax to declare one or more variables:
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
45
Putting Data into Variables
• A variable is said to be initialized the first time you
place a value into it.
• A variable that has not been initialized will hold an
unpredictable “garbage” value. Visual Studio gives
an error message if you use an uninitialized variable
in an expression.
• Ways to place data into a variable:
– Use an assignment statement.
– Use input (read) statements to let the user enter values
from the keyboard.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
46
Assignment Statement
• The assignment statement takes the form:
• The expression on the right side is evaluated and its
value is assigned to the variable on the left side.
• Examples:
dailyRate = 0.0002;
annualRate = 365 * dailyRate;
• In C++, = is called the assignment operator.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
47
Assignment Statement (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
48
Declaring & Initializing Variables
• You can use the assignment operator to initialize a
variable in the same statement that declares it.
• Examples:
int first = 13, second = 10;
char ch = ' ';
double x = 12.6;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
49
Assignment Versus Equality
•
•
The = operator in C++ has a different
meaning from the meaning it has in your
math classes.
Example: in a math class, the following
statement cannot be true:
x = x + 1;
•
But this is a perfectly good (and
frequently used) C++ statement. It tells
the program to increase x’s value by 1.
Increment and Decrement Operators
• The increment operator ++ increases a variable by 1.
– Example: The statement
++x;
does the same thing as the statement
x = x + 1;
• Similarly, the decrement operator -- decreases a
variable’s value by 1.
– Example: The statement
--x;
does the same thing as the statement
x = x - 1;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
51
Pre- and Post-Increment/Decrement
• These operators’ behavior depends on whether
they’re placed before or after the variable name.
– Pre-increment: ++variable increments the variable, and then uses
the incremented value in the expression.
– Post-increment: variable++ uses the variable’s original value in
the expression, and then increments the variable.
• What is the difference between the following?
x = 5;
y = ++x;
x = 5;
y = x++;
• Similarly for pre-decrement (--variable) and postdecrement (variable--).
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
52
Input (Read) Statement
• cin is used with >> to let the user enter a value.
• This is called an input statement (or read statement).
• The operator >> is the stream extraction operator.
• For example, if miles is a double variable, the following
statement causes computer to get a value of type double
from the keyboard and place it in the variable miles:
cin >> miles;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
53
Input (Read) Statement (cont’d.)
• A single input statement can assign values to more
than one variable.
• Example: if feet and inches are variables of type
int, the following statement reads two integers
from the keyboard and places these integer values in
feet and inches respectively. :
cin >> feet >> inches;
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
54
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
55
Output Statement
• cout is used with << to display values on the
screen:
• This is called an output statement.
• The operator << is the stream insertion operator.
• The expression is evaluated and its value is printed at
the current cursor position on the screen.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
56
Manipulators in Output Statements
• You can use manipulators to format the output.
– Example: the manipulator endl causes the cursor to move
to beginning of the next line.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
57
Escape Sequences in Output
Statements
• Escape sequences are another way to format
output. Example: The new line character is '\n'
cout << "Hello there.";
cout << "My name is James.";
Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";
Output :
Hello there.
My name is James.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
58
Escape Sequences in Output
Statements (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
59
The Standard Library
• The core C++ language has a relatively small number
of built-in operations.
• Many other useful operations are provided as a
collection of files called the C++ Standard Library.
• These library files make your job easier, because they
save you from having to re-invent the wheel when
you want to perform common tasks.
• A big part of becoming a C++ programmer is learning
about the many library files in the Standard Library.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
60
The Standard Library (cont’d.)
• Each library file (or “header file”) has a name,
which is typically written inside angle
brackets.
– Examples:
• <iostream>
• <string>
• <cmath>
• The next slides show how to tell the compiler that
you want to use operations from one or more of
these files.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
61
Preprocessor Directives
• Your programs will often
contain preprocessor
directives. These are
commands that the
preprocessor program
executes before your
program is compiled.
• All preprocessor
directives begin with #.
• No semicolon at the end of these directives.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
62
The #include Directive
• The most common preprocessor directive is
#include, which is how you tell the compiler that
you want to use a Standard Library file.
• Syntax to include a header file:
• For example:
#include <iostream>
– Causes the preprocessor to include the header file
iostream in the program. Without this, you could not
use cout or cin in your program.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
63
namespace and Using cin and cout in
a Program
• cin and cout are declared in the header file
iostream, but within the std namespace.
• To use cin or cout in a program, use the following
two statements:
#include <iostream>
using namespace std;
• Without that using statement, you would need to
type std::cin instead of cin throughout your
program.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
64
Using the string Data Type in a
Program
• Recall that the string data type is not built
into the core C++ language. It’s a programmerdefined type defined in the C++ Standard
Library.
• To use the string type, you need to access
its definition from the header file string.
• Use the following preprocessor directive:
#include <string>
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
65
The main Function
• A function is a named block of code that
performs some well-defined set of operations.
• Every C++ program must contain a function
named main. This is where execution begins
when you run the program.
• Complex programs contain many functions,
but for now most of your programs will only
contain the main function.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
66
The main Function (cont’d.)
• The first line of a
function is called
the function’s
heading:
int main()
• The statements
enclosed between
the curly braces
{ and } form the
function’s body.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
67
Named Constants
• Named constant: memory location whose content
cannot change during execution.
• Syntax to declare a named constant:
• By convention, constant identifiers are all upper-case.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
68
Syntax Errors
• Syntax rules: indicate what is legal and what is not
legal.
– Example of a syntax rule: Every C++ statement
must end with a semicolon.
• The compiler finds and reports syntax errors during
compilation. It won’t let you run the program until
you fix these errors.
int x;
int y
//Line 1
//Line 2: Syntax error
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
69
Semantic Errors
• Semantic rules: set of rules that gives meaning to a
language.
• A program with no syntax errors may still not
produce correct results.
• Example: 2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but have
different meanings. So if you use one of these
expressions where you should use the other one,
your program will produce incorrect results.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
70
Prompt Lines
• Prompt lines are statements that tell the user what
to do.
cout << "Please enter a number between 1 and 10 and "
<< "press the return key." << endl;
cin >> num;
• Always include a correctly spelled, properly
punctuated prompt line when you want the user to
enter some input.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
71
Documentation
• A well-documented program is easier to understand
and modify.
• Two keys to good documentation:
1. Use comments.
2. Choose meaningful variable names.
• Comments should:
– Explain the purpose of the program.
– Identify who wrote it, and when.
– Explain the purpose of particular statements whose
meaning is not obvious.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
72
Documentation (cont’d.)
• Variable names should be self-documenting:
– Example: use CENTIMETERS_PER_INCH instead of X.
• Avoid run-together words, such as annualsale.
This is hard to read.
– Solution:
• Either capitalize the beginning of each new word:
annualSale
• Or insert an underscore just before a new word:
annual_sale
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
73
Compound Assignment Statements
• In addition to the simple assignment operator =, C++
provides several compound assignment operators,
including:
+=
-=
*=
/=
%=
• Simple assignment statement:
x = x * y;
• Equivalent compound assignment statement:
x *= y;
• Their sole purpose is to provide more concise
notation. But you don’t need to use them.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
74
Download