chapters 1 - 5 reviewcourses.cs.vt.edu/~cs1044/spring09/lectures/lec 9 - review_test_1.… · 2...

74
1 Chapters 1 - 5 Review

Upload: others

Post on 26-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

1

Chapters 1 - 5

Review

Page 2: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 3: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

. . .

Page 4: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

4

Programming Life Cycle Phases

• Problem-Solving

• Implementation

• Maintenance

Page 5: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 6: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 7: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 8: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 9: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

9

An Important Problem Solving

Technique

Divide and conquer -- break up large problems into manageable units

Functions

Page 10: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 11: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

Page 12: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 13: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 14: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 15: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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:

Page 16: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 17: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 18: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 19: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 20: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 21: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 22: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

Page 23: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 24: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 25: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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 = ?

Page 26: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

26

Prefix Form

Increment Operator

8

int age;

age = 8;

++age;

age

9

age

Page 27: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

27

Postfix Form

Increment Operator

8

int age;

age = 8;

age++;

age

9

age

Page 28: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

28

Precedence

Higher Precedence determines

which operator is applied first in an

expression having several

operators

Page 29: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

29

Some C++ Operators

Precedence Operator Description

Higher ( ) Function call

+ Positive

- Negative

* Multiplication

/ Division

% Modulus(remainder)

+ Addition

- Subtraction

Lower = Assignment

Page 30: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 31: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 32: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 33: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 34: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 35: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 36: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 37: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 38: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 39: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

Page 40: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 41: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

}

Page 42: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

42

OUTPUT

Number is 123.459

Value is rounded if necessary to be displayed

with exactly 3 places after the decimal point

Page 43: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 44: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 45: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

}

Page 46: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

46

Output

12345678901234567890

Mine Yours

123 5

Each is displayed right-justified and

each is located in a total of 10 positions

position

Page 47: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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;

}

Page 48: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 49: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 50: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 51: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 52: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 53: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 54: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 55: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 56: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 57: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 58: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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)

Page 59: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

C++ Control Structures

Selection

if

if . . . else

switch

Repetition

for loop

while loop

do . . . while loop

Page 60: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

Expressions

Control structures use logical expressions to

make choices, which may include:

6 Relational Operators

< <= > >= == !=

3 Logical Operators

! && ||

Page 61: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 62: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 63: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

“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

Page 64: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 65: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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”;

Page 66: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

if (number == 0) if (! number )

{ { . .

. .

. .

} }

Each expression is only true when

number has value 0

These are equivalent. Why?

Page 67: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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 . . .

Page 68: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.”

Page 69: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 70: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 71: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 72: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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.

Page 73: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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

Page 74: Chapters 1 - 5 Reviewcourses.cs.vt.edu/~cs1044/spring09/Lectures/Lec 9 - Review_Test_1.… · 2 Chapter 1 Topics Computer Programming Programming Life-Cycle Phases Creating an Algorithm

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