Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2...
Transcript of Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2...
1
Chapters 1 - 5
Review
2
Chapter 1 Topics
Computer Programming
Programming Life-Cycle Phases
Creating an Algorithm
Machine Language vs. High Level Languages
Compilation and Execution Processes
C++ History
Computer Components
Computing Profession Ethics
Problem-Solving Techniques
3
What is Computer Programming?
It is the process of planning a sequence of
steps(called instructions) for a computer
to follow.
STEP 1
STEP 2
STEP 3
. . .
4
Programming Life Cycle Phases
• Problem-Solving
• Implementation
• Maintenance
5
Problem-Solving Phase
Analyze the problem and specify what the solution must do
Develop a general solution(algorithm) to solve the problem
Verify that your solution really solves the problem
6
An Algorithm
An algorithm is a step-by-step
procedure for solving a problem
with a finite amount of data
in a finite amount of time
7
More Problem Solving Techniques
Divide and conquer -- break up large problems into manageable units
Building-block approach -- can you solve small pieces of the problem?
Merge solutions -- instead of joining them end to end to avoid duplicate steps
Overcome mental block -- by rewriting the problem in your own words
8
Chapter 2 Topics
Programs Composed of Several Functions
Syntax Templates
Legal C++ Identifiers
Assigning Values to Variables
Declaring Named Constants
String Concatenation
Output Statements
C++ Program Comments
9
An Important Problem Solving
Technique
Divide and conquer -- break up large problems into manageable units
Functions
10
A C++ program is a collection
of one or more functions
There must be a function called main()
Execution always begins with the first
statement in function main()
Any other functions in your program are
subprograms and are not executed until
they are called
11
Syntax and Semanticssyntax (grammar) rules that specify how valid instructions (constructs) are written
semantics rules that specify the meaning of syntactically valid instructions
The syntax of an assignment statement requires that you have:
l-value = expression;
where l-value is something, like a variable, whose value can be changed, and expression is a valid C++ expression.
The semantic rule for an assignment statement specifies that the value of the expression on the right side is stored in the l-value on the left side. For example:
const int totalDays = 25567; // NOT an l-value
int daysPassed; // l-values
int daysLeft;
daysPassed = 17094;
daysLeft = totalDays - daysPassed;
12
What is an Identifier?
An identifier is the name used for a data object(a variable or a constant), or for a function, in a C++ program
Beware: C++ is a case-sensitive language
Using meaningful identifiers is a good programming practice
13
What is a Variable?
A variable is a location in memory
that can be referred to by an
identifier and in which a data value
that can be changed is stored
Declaring a variable means
specifying both its name and its
data type
14
What Does a
Variable Declaration Do?
A declaration tells the compiler to allocate enough
memory to hold a value of this data type and to
associate the identifier with this location
int ageOfDog;
float taxRate;
char middleInitial;
4 bytes for taxRateY2K 1 byte for
middleInitial
15
Initialization• Declaring a variable does not (usually) automatically provide it with a
specific starting value.
• A variable is just a name for a location in the computer's memory.
• Memory cannot be "empty", it always stores some value.
•For all practical purposes, the variable declarations on the previous
slide create variables whose initial values are random garbage,
whatever happens to be at the corresponding location in memory when
the program is executed.
• Using the value of a variable that has not yet been properly set is one of
the most common sources of errors in programs.
int Weight = 0,
Height = 0,
Length = 0;
double ClassAverage = 0.0, GPA = 0.0;
string Major;
Major = "Computer Science";
Therefore, it is good practice to
always give every newly declared
variable a specific initial value.
This can be combined with the
declaration or accomplished via a
later assignment:
16
Insertion Operator(<<)
Variable cout is predefined to denote an output
stream that goes to the standard output
device(display screen)
The insertion operator << called “put to” takes
2 operands
The left operand is a stream expression, such as
cout
The right operand is an expression of a simple
type or a string constant
17
Categories of Programming Errors
Language syntax (compilation) errors:
- Error is in the form of the statement:misspelled word, unmatched parenthesis,comma out of place, etc.
- Error is detected by the compiler (at compiletime).
- Compiler cannot correct error.
- Compiler prints error messages, but usuallycontinues to compile.
18
Categories of Programming Errors
Linking errors:
- Error is typically in the form of the declarationor implementation or call of a function.
- Error may also result from including thewrong header file.
- Error is detected by the linker (after thecompiler has produced an object file).
- Linker cannot correct error, so no executablefile is generated.
19
Categories of Programming Errors Execution (runtime) errors:
- Error occurs while the program is running, causingthe program to "crash" (terminate abnormally.
- Frequently an illegal operation of some sort.Arithmetic errors like an attempt to divide by zero,Access violations: try to use some resource like amemory address that is not allocated to it.
- Code compiles and links without errors.
- Unfortunately, some operating systems do not reliablydetect and respond to some kinds of execution errors.In that case, an incorrect program may appear tofunction correctly on one computer but not onanother.
20
Categories of Programming Errors Logic errors:
- Error occurs while the program is running, causingthe production of incorrect results, but notnecessarily a runtime "crash".
- Program source code compiles and links withouterrors – no help there.
- Logic errors are detected by checking resultscomputed by the program.
- The cause(s) of the error must be determined by alogical analysis of the error and the source code.This must be done by the developer. This is thehardest type of error to deal with.
21
Analyze the problem statement
Design a solution
Enter/edit source code
Compile/link source code
Compiler/Linker errors?
Test the program
Results incorrect?
Execution errors?
Find error in source code
check syntax
Find cause of runtime error
check code
check input data
rethink analysis/design
Find cause of logic error
check code
check input data
rethink analysis/design
Success!
At least with this input.
yesno
no
no
yes
yes
or
or
Comments It is good practice to include descriptive comments in code.
Comments may explain the purpose of a declared identifier,
or of a statement or group of statements that perform some
calculation, or input or output.
22
int quizScore; // score on a quiz
int numQuizzes = 0; // number of quizzes given
int totalPoints; // sum of all quiz scores
double quizAverage; // average of all quiz scores
/* Read in quiz scores until the user enters
one that's negative. */
cin >> quizScore;
while (quizScore >= 0) {
totalPoints = totalPoints + quizScore;
numQuizzes = numQuizzes + 1;
cin >> quizScore;
}
// Calculate average quiz score:
quizAverage = double(totalPoints) / numQuizzes;
23
Chapter 3 Topics
Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type
Conversion Calling a Value-Returning Function Using Function Arguments Using C++ Library Functions in
Expressions Calling a Void Function C++ Manipulators to Format Output String Operations length,find,and substr
24
Division Operator
The result of the division operator depends on the type of its operands
If one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type
Examples11 / 4 has value 211.0 / 4.0 has value 2.7511 / 4.0 has value 2.75
25
Modulus Operator
Its result is the integer type remainder of
an integer division
The modulus operator % can only be used
with integer type operands and always has
an integer type result
Example
11 % 4 has value 3 because
)4 11
R = ?
26
Prefix Form
Increment Operator
8
int age;
age = 8;
++age;
age
9
age
27
Postfix Form
Increment Operator
8
int age;
age = 8;
age++;
age
9
age
28
Precedence
Higher Precedence determines
which operator is applied first in an
expression having several
operators
29
Some C++ Operators
Precedence Operator Description
Higher ( ) Function call
+ Positive
- Negative
* Multiplication
/ Division
% Modulus(remainder)
+ Addition
- Subtraction
Lower = Assignment
30
Associativity
Left to right associativity means that in an expression having 2 operators with the same priority, the left operator is applied first
In C++ the binary operators
*, /, %, +, - are all left associative
Expression 9 - 5 - 1 means(9 - 5) - 1
4 - 1
3
31
7 * 10 - 5 % 3 * 4 + 9
(7 * 10) - 5 % 3 * 4 + 9
70 - 5 % 3 * 4 + 9
70 -(5 % 3) * 4 + 9
70 - 2 * 4 + 9
70 -( 2 * 4) + 9
70 - 8 + 9
(70 - 8 ) + 9
62 + 9
71
Evaluate the Expression
32
Parentheses
Parentheses can be used to change
the usual order
Parts in() are evaluated first
Evaluate (7 *(10 - 5) % 3) * 4 + 9
(7 * 5 % 3 ) * 4 + 9
( 35 % 3) * 4 + 9
2 * 4 + 9
8 + 9
17
33
Variable = Expression
First, Expression on right is evaluated
Then the resulting value is stored in the memory location of Variable on left
NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable
Recall Assignment Operator Syntax
34
Type Casting is Explicit
Conversion of Type
int(4.8) has value 4
float(5) has value 5.0
float(7/4) has value 1.0
float(7) / float(4) has value 1.75
35
Some Expressionsint age;
Example Value
age = 8; 8
- age; - 8
5 + 8; 13
5 / 8; 0
6.0 / 5.0 ; 1.2
float(4 / 8) ; 0.0
float(4) / 8 ; 0.5
cout << “How old are you?”; cout
cin >> age; cin
cout << age; cout
Two Kinds of Functions
Always returns
a single value to
its caller and is
called from within
an expression
Never returns a
value to its caller
and is called as a
separate
statement
Value-Returning Void
36
37
Manipulators
Manipulators are used only in input and
output statements
endl, fixed, showpoint, setw, and
setprecision are manipulators that can be
used to control output format
endl is use to terminate the current output
line and create blank lines in output
38
Insertion Operator(<<)
The insertion operator << takes 2
operands
The left operand is a stream expression,
such as cout
The right operand is an expression of
simple type, a string, or a manipulator
39
Using Manipulators
Fixed and Showpoint use the following statement to specify
that(for output sent to the cout stream)
decimal format(not scientific notation) be
used, and that a decimal point be
included(even for floating values with 0 as
fractional part)
cout << fixed << showpoint;
40
setprecision(n)
Requires #include <iomanip> and appears in
an expression using insertion operator(<<)
If fixed has already been specified, argument
n determines the number of places displayed
after the decimal point for floating point
values
Remains in effect until explicitly changed by
another call to setprecision
41
What is exact output?#include <iomanip> // For setw() and setprecision()
#include <iostream>
using namespace std;
int main()
{
float myNumber = 123.4587;
cout << fixed << showpoint;
// Use decimal format
// Print decimal points
cout << “Number is ” << setprecision(3)
<< myNumber << endl;
return 0;
}
42
OUTPUT
Number is 123.459
Value is rounded if necessary to be displayed
with exactly 3 places after the decimal point
43
Manipulator setw
“Set width” lets us control how many character
positions the next data item should occupy
when it is output
setw is only for formatting numbers and strings,
not char type data
44
setw(n)
Requires #include <iomanip> and appears in an
expression using insertion operator(<<)
Argument n is called the fieldwidth specification,
and determines the number of character positions
in which to display a right-justified number or
string(not char data); the number of positions
used is expanded if n is too narrow
“Set width” affects only the very next item
displayed and is useful to align columns of output
45
What is exact output?#include <iomanip> // For setw()
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myNumber = 123;
int yourNumber = 5;
cout << setw(10) << “Mine”
<< setw(10) << “Yours” << endl
<< setw(10) << myNumber
<< setw(10) << yourNumber << endl;
return 0;
}
46
Output
12345678901234567890
Mine Yours
123 5
Each is displayed right-justified and
each is located in a total of 10 positions
position
47
What is exact output?#include <iomanip> // For setw() and setprecision()
#include <iostream>
using namespace std;
int main()
{
float myNumber = 123.4;
float yourNumber = 3.14159;
cout << fixed << showpoint;
// Use decimal format; print decimal points
cout << “Numbers are: ” << setprecision(4)
<< endl << setw(10) << myNumber
<< endl << setw(10) << yourNumber
<< endl;
return 0;
}
48
OUTPUT
Numbers are:
123.4000
3.1416
Each is displayed right-justified and
rounded if necessary and each is
located in a total of 10 positions with
4 places after the decimal point
12345678901234567890
49
float x = 312.0;
float y = 4.827;
cout << fixed << showpoint; OUTPUT
cout << setprecision(2)
<< setw(10) << x << endl 3 1 2.00
<< setw(10) << y << endl; 4.83
cout << setprecision(1)
<< setw(10) << x << endl 3 1 2.0
<< setw(10) << y << endl; 4.8
cout << setprecision(5)
<< setw(7) << x << endl 3 1 2.00000
<< setw(7) << y << endl; 4.82700
More Examplesx312.0
y
4.827
49
50
Chapter 4 Topics
Input Statements to Read Values into a Program using >>, and functions get, ignore, getline
Prompting for Interactive Input/Output
Using Data Files for Input and Output
Object-Oriented Design Principles
Functional Decomposition Methodology
Extraction Operator(>>)
Variable cin is predefined to denote an input
stream from the standard input device(the
keyboard)
The extraction operator >> called “get from” takes
2 operands; the left operand is a stream
expression, such as cin--the right operand is a
variable of simple type
Operator >> attempts to extract the next item from
the input stream and to store its value in the right
operand variable
51
Whitespace Characters Include . . .
blanks
tabs
end-of-line(newline) characters
The newline character is created by
hitting Enter or Return at the keyboard,
or by using the manipulator endl or “\n”
in a program
52
Extraction Operator >>
>> “skips over” (actually reads but does
not store anywhere) leading white space
characters as it reads your data from the
input stream(either keyboard or disk file)
53
54
getline(inFileStream, str)
getline does not skip leading whitespace
characters such as blanks and newlines
getline reads successive characters(including
blanks) into the string, and stops when it reaches
the newline character „\n‟
The newline is consumed by getline, but is not
stored into the string variable
Opening a File
Opening a file
Associates the C++ identifier for your file with
the physical(disk) name for the file
– If the input file does not exist on disk, open is not
successful
– If the output file does not exist on disk, a new file with
that name is created
– If the output file already exists, it is erased
Places a file reading marker at the very
beginning of the file, pointing to the first
character in the file
55
Stream Fail State
When a stream enters the fail state,
Further I/O operations using that stream have
no effect at all
The computer does not automatically halt the
program or give any error message
Possible reasons for entering fail state include
Invalid input data (often the wrong type)
Opening an input file that doesn‟t exist
Opening an output file on a disk that is already
full or is write-protected
56
Chapter 5 Topics
Data Type bool
Using Relational and Logical Operators to
Construct and Evaluate Logical Expressions
If-Then-Else Statements
If-Then Statements
Nested If Statements for Multi-way Branching
Testing the State of an I/O Stream
Testing a C++ Program
Flow of Control
Sequential unless a “control structure” is
used to change the order
Two general types of control structures
Selection (also called branching)
Repetition (also called looping)
C++ Control Structures
Selection
if
if . . . else
switch
Repetition
for loop
while loop
do . . . while loop
Expressions
Control structures use logical expressions to
make choices, which may include:
6 Relational Operators
< <= > >= == !=
3 Logical Operators
! && ||
Operator Meaning Associativity
! NOT Right
*, / , % Multiplication, Division, Modulus Left
+ , - Addition, Subtraction Left
< Less than Left
<= Less than or equal to Left
> Greater than Left
>= Greater than or equal to Left
== Is equal to Left
!= Is not equal to Left
&& AND Left
|| OR Left
= Assignment Right 61
Logical
Expression Meaning Description
! p NOT p ! p is false if p is true
! p is true if p is false
p && q p AND q p && q is true if
both p and q are true.
It is false otherwise.
p || q p OR q p || q is true if either
p or q or both are true.
It is false otherwise.
“Short-Circuit” Evaluation
C++ uses short circuit evaluation of logical
expressions
This means logical expressions are evaluated
left to right and evaluation stops as soon as
the final truth value can be determined
Use Precedence Chart
int number;
float x;
number != 0 && x < 1 / number
/ has highest priority
< next priority
!= next priority
&& next priority
What happens if Number has value 0?
Run Time Error (Division by zero) occurs
Omitting Braces
Braces can be omitted only when a clause is
a single statement
if (lastInitial <= „K‟)
volume = 1;
else
volume = 2;
cout << “Look it up in volume # “
<< volume << “ of NYC phone book”;
if (number == 0) if (! number )
{ { . .
. .
. .
} }
Each expression is only true when
number has value 0
These are equivalent. Why?
Nested If Statements
Each Expression is evaluated in sequence, until
some Expression is found that is true
Only the specific Statement following that particular
true Expression is executed
If no Expression is true, the Statement following the
final else is executed
Actually, the final else and final Statement are
optional, and if omitted and no Expression is true,
then no Statement is executed
An example . . .
Example
Write a void function DisplayMessage that
you can call from main to describe the
pollution index value it receives as an
argument
Your city describes a pollution index
less than 35 as “Pleasant”,
35 through 60 as “Unpleasant”,
above 60 as “Health Hazard.”
In the absence of braces,an else is always paired with the closest
preceding if that doesn’t already have an
else paired with it
Extraction Operator and WhitespaceIn programming, common characters that do not produce a visible image on a page or in a file are referred to as whitespace.
The most common whitespace characters are:
Name Code
newline \n
tab \t
blank (space)
carriage return \r
vertical tab \v
By default, the extraction operator in C++ will ignore leading whitespace characters.
That is, the extraction operator will remove leading whitespace characters from the input stream and discard them.
What if we need to read and store whitespace characters? See the get()
function later in the notes.
Details of an Extraction
int X ; char Y ; double Z;
cin >> X >> Y >> Z;
Assume the input stream cin contains: 173 .12 -19
The numbers are separated by some sort of whitespace, say by tabs.
Suppose that X is declared as an int, and the following statement is executed:
The type of the targeted variable, X in this case, determines how the extraction is
performed.
First, any leading whitespace characters are discarded.
Since an integer value is being read, the extraction will stop if a character that
couldn't be part of an integer is found.
So, the digits '1' and '2' are extracted, and the next character is a tab, so the extraction stops and X gets the value 12.
The tab after the '2' is left in the input stream.
ignore() Member FunctionThere is also a way to remove and discard characters from an input stream:
cin.ignore(N, ch);
means to skip (read and discard) up to N characters in the input stream, oruntil the character ch has been read and discarded, whichever comes first. So:
cin.ignore(80, '\n');
says to skip the next 80 input characters or to skip characters until a newline character is read, whichever comes first.
The ignore function can be used to skip a specific number of characters or halt whenever a given character occurs:
cin.ignore(100, '\t');
means to skip the next 100 input characters, or until a tab character is read, or whichever comes first.
C++ also provides stream types for reading from and writing to files stored on
disk. For the most part, these operate in exactly the same way as the standard I/O streams, cin and cout.
For basic file I/O: #include <fstream>
There are no pre-defined file stream variables, so a programmer who needs to
use file streams must declare file stream variables:
int x;
ifstream inFile; // input file stream object
ofstream outFile; // output file stream object
The types ifstream and ofstream are C++ stream classes designed to be
connected to input or output files.
File stream objects have all the member functions and manipulators possessed by the standard streams, cin and cout.
Streams for File I/O
In addition, to activate the manipulator setprecision( )for your output stream,
insert the following two manipulators once:
outStream << fixed << showpoint;
(Just use the name of your output stream variable.)
Omitting these manipulators will cause setprecision( ) to fail, and will cause
real values whose decimal part is zero to be printed without trailing zeroes regardless of setprecision( ).
Floating Point Formatting
Other useful manipulators:
bin
hex
octal
dec
scientific