Computer Science I - PowerPoint PPT Presentation

1 / 487
About This Presentation
Title:

Computer Science I

Description:

Developed by John Backus at IBM in 1957. Designed for scientific ... Java was developed by James Gosling at Sun Microsytems in 1995. 100% object-oriented. ... – PowerPoint PPT presentation

Number of Views:77
Avg rating:3.0/5.0
Slides: 488
Provided by: peopl93
Category:

less

Transcript and Presenter's Notes

Title: Computer Science I


1
Computer Science I
  • Dr. Robb T. Koether
  • Fall 2002

2
Introduction and History of C
  • Lecture 1 Aug 28, 2002

3
Introduction
  • See the syllabus.

4
Earlier Languages FORTRAN
  • FORTRAN
  • FORmula TRANslation.
  • Developed by John Backus at IBM in 1957.
  • Designed for scientific computations.

5
Earlier Languages BASIC
  • BASIC.
  • Beginner's All-purpose Symbolic Instruction Code.
  • Developed by John Kemeny in 1964 at Dartmouth
    College.
  • Designed for elementary beginning programming.

6
Earlier Languages Pascal
  • Pascal
  • Named after Blaise Pascal.
  • Developed by Niklaus Wirth in 1972.
  • Designed for the teaching of programming
    concepts.

7
Earlier Languages C
  • C Language
  • A, B, C.
  • Developed by Brian Kernighan and Dennis Ritchie
    in 1978 at Bell Labs.
  • Designed to give the programmer greater control
    over the computer.
  • Syntax is less readable than the other popular
    languages.

8
The C Language
  • C was developed by Bjarne Stroustrup in 1983 at
    Bell Labs.
  • C contains C as a sublanguage.
  • Its language structures supports a more highly
    organized programming style than C did.

9
The C Language
  • C is an object-oriented language.
  • Maps concepts to data types.
  • Builds hierarchies of related data types.
  • Number ? Point ? Line ? Segment.
  • The programmer may create his own data types.

10
The Java Language
  • Java was developed by James Gosling at Sun
    Microsytems in 1995.
  • 100 object-oriented.
  • Platform-independent.
  • Incorporates a Graphical User Interface (GUI).
  • Intended to be an improvement over C.
  • Easier (?) to use.
  • Less error-prone.

11
Computers and Programs
  • Chapter 1

12
Computer Organization and Binary Numbers
  • Lecture 2 Aug 29, 2002

13
The Main Components
  • The Central Processing Unit (CPU)
  • Memory
  • Input devices
  • Output devices

14
The CPU
  • Performs arithmetic.
  • Addition, subtraction.
  • Makes logical decisions.
  • Branch if two values are equal, etc.
  • Loads data from memory.
  • Stores data in memory.

15
Memory
  • Registers (in the CPU)
  • Level 1 Cache (L1)
  • Holds commonly used data.
  • 10 of the data is used 90 of the time.
  • Level 2 Cache (L2)
  • Holds less commonly used data.
  • 90 of the data is used 10 of the time.
  • Main Memory
  • Holds data that is seldom used.

16
Representing Data
  • How can a machine store a number?
  • Design a machine that can be put into different
    states.
  • Each state represents a value.
  • For example, the values 0 through 9 may be
    represented by 10 different states.

17
Representation of Data
  • How could we represent the values 0 through 99?
  • Build a machine with 100 states.
  • Or, build two machines with 10 states each.
  • One machine represents the 1s digit.
  • The other machine represents the 10s digit.
  • With six 10-state machines, we could represent
    values from 0 to 999999.

18
Binary Representation of Data
  • In computers, it is more efficient to use only
    two states.
  • a light on/off
  • a switch open/closed
  • a voltage high/low
  • Therefore, numbers will be stored in binary
    rather than decimal.

19
Binary Representation of Data
  • One-bit numbers can represent two different
    values 0 or 1.
  • With 2 bits, we can represent four different
    values, representing 0 through 3.

20
Binary Representation of Data
  • With 3 bits, we can represent 8 values,
    representing 0 through 7.

21
Fixed-Length Binary Numbers
  • In general, n bits can represent any of 2n
    different values, ranging from 0 to 2n ? 1.
  • 4 bits represent values from 0 to 15.
  • 8 bits represent values from 0 to 255.
  • 16 bits represent values from 0 to 65535.
  • Etc.

22
Binary Number System
  • In the binary number system, each position in the
    number represents a power of 2.
  • Example 101011 represents
  • 1 ? 25 0 ? 24 1 ? 23 0 ? 22 1 ? 21 1 ?
    20
  • which equals 32 8 2 1 43.

23
The Structure of Memory
  • 1 bit 1 binary digit (0 or 1).
  • 1 half-byte (nibble) 4 bits.
  • 1 byte 8 bits.
  • 1 half-word 2 bytes 16 bits.
  • 1 word 4 bytes 32 bits (standard size).
  • 1 kilobyte (K) 1024 bytes 210 bytes.
  • 1 megabyte (M) 1024 K 210 K.
  • 1 gigabyte (G) 1024 M 210 M, etc.

24
Hexadecimal Numbers
  • For convenience, we often display values in
    hexadecimal (base 16).
  • Hexadecimal has 16 digits with values 0 through
    15 (0 9 and A F).

25
Examples of Hexadecimal Numbers
  • 123 (hex) 1 ? 162 2 ? 16 3 292 (dec).
  • FF 15 ? 16 15 255.
  • FACE 15 ? 163 10 ? 162 12 ? 16 14
  • 61440 2560 192 14
  • 64206.

26
Hexadecimal Numbers
  • Hexadecimal numbers are convenient because
  • They are compact.
  • There is a very simple relation between them and
    binary numbers.
  • One hexadecimal digit represents a 4-digit binary
    number (values 0 15).

27
Conversion from Hexadecimal to Binary
  • Convert 2B6F to binary
  • Write each hex digit as a 4-bit binary number.
  • 2 0010
  • B 1011
  • 6 0101
  • F 1111
  • Write the 4-bit numbers together as a single
    binary number
  • 0010101101011111

28
Conversion from Binary to Hexadecimal
  • Convert 1001101011101011 to hexadecimal.
  • Break it up into groups of 4 bits (starting on
    the right).
  • 1001 1010 1110 1011
  • Write each block of 4 as a hex digit.
  • 9 A E B
  • Write the hex digits as a single hex number.
  • 9AEB

29
Programming Languages
  • Lecture 3 Aug 30, 2002

30
High-Level Languages
  • Instructions use some English words (if, else,
    while, etc.)
  • Expressions are written in common algebraic
    notation.

int a 10 // Assign 10 to a int b 20 //
Assign 20 to b int c a b // Assign a b to c
31
Assembly Language
  • Each instruction represents a single operation
    (add, multiply, compare, etc.)
  • Mnemonics are used instead of words.

moveq 10,d3 Move 10 to data reg 3 moveq
20,d4 Move 20 to data reg 4move.l d3,d5 Move
reg 3 to reg 5add.l d4,d5 Add reg 4 to reg 5
32
Machine Language
  • Each instruction represents a single operation.
  • Each instruction is written entirely numerically.

33
Program Translation
  • A computer is capable of interpreting and
    executing only machine language instructions.
  • Humans (almost always) write programs in
    high-level languages such as C.
  • Therefore, a C program must be translated into
    machine language in order to be run.

34
Compilers
  • A compiler translates a high-level language such
    as C into machine language.
  • The compiler must first check the syntax of the
    source code.
  • A syntax error is a violation of the grammar
    rules of the language.
  • If there are no syntax errors, then the compiler
    produces the object code.

35
Linkers
  • A linker combines the object code produced by the
    compiler with library functions (e.g., the square
    root function) needed by the program.
  • If the linker is unable to locate a function, it
    reports a link error.
  • If there are no link errors, the linker produces
    a fully functioning program.

36
Loaders
  • The loader copies the program into a suitable
    location in main memory and begins execution.
  • A run-time (or logical) error is an error that
    occurs during execution.
  • Typically, run-time errors cannot be detected by
    the compiler before execution.
  • Division by zero would be a run-time error.

37
Assemblers
  • An assembler translates an assembly language
    program into machine language.
  • Many compilers produce assembly code as an
    intermediate step, and then invoke an assembler
    to finish the translation.
  • A disassembler creates assembly code from object
    code.
  • This makes the object code more readable.

38
The C Program Hierarchy
  • A statement, typically, performs a single task.
  • For example, evaluate a formula
  • A function is a group of statements that
    accomplishes a single task.
  • For example, insert a new name into a list of
    names.
  • A file contains a group of related functions.
  • A program consists of a collection of files.

39
Statements
  • A statement is a one-line instruction.
  • A statement, typically, performs a single action.
  • Examples
  • Evaluate a formula.
  • Print a line of output.
  • Make a yes/no decision.

40
Functions
  • A function consists of several statements which
    together perform a single task as a component of
    a larger problem.
  • Each function is given a name.
  • Execution begins in the function main().
  • Examples
  • Find the average of a set of numbers.
  • Insert a new name into a list of names.

41
Files
  • A file consists of a set of functions having
    something in common.
  • Each file is stored separately under its own
    name.
  • Files are compiled separately from each other, to
    be linked later.

42
Projects
  • A project consists of several files containing
    all the functions which, when linked together,
    will solve a problem.
  • The project is given a name.

43
C The Fundamentals
  • Chapter 2

44
Elementary Data Types
  • Lecture 4 Sep 2, 2002

45
Integer Types
  • Integers are stored as binary numbers.
  • An n-bit integer can hold any of 2n different
    values.
  • Integer types are either signed or unsigned.
  • Integer constants must not have a decimal point.

int a 123
46
Integer Types
  • short 2 bytes
  • int 4 bytes
  • long 4 bytes
  • long long 8 bytes
  • Each type can be either signed or unsigned.

unsigned int a 123
47
Signed vs. Unsigned Integers
  • Unsigned integers.
  • An unsigned integer cannot be negative.
  • All of its bits constitute the numbers.
  • Values range from 0 to 2n 1.
  • Signed integers
  • A signed integer can be positive or negative.
  • 1 bit is the signed bit.
  • Remaining n 1 bits constitute the number.
  • Values range from 2n 1 to 2n 1 1.

48
Ranges of Values of the Integer Types
49
Integer Overflow
  • What happens when an integer value becomes too
    large?
  • That is, what if we assign to an integer the
    largest legal value, and then add 1?
  • Example
  • IntLimitTest.cpp

50
Floating-Point Types
  • Floating-point numbers are stored in two parts.
  • The mantissa contains the significant digits.
  • The exponent locates the decimal point.
  • Floating-point constants must have a decimal
    point.

51
Single-Precision Numbers
  • Single-precision floating point numbers (floats)
    occupy 4 bytes of memory.
  • 8-bit exponent
  • 24-bit mantissa
  • The values range from a minimum of ?1.17549
    10?38 to a maximum of ?3.40282 1038.
  • Approximately 7-place precision.

float x 12.34567
52
Double-Precision Numbers
  • Double-precision floating point numbers (doubles)
    occupy 8 bytes of memory.
  • 11-bit exponent
  • 53-bit mantissa
  • The values range from a minimum of ?2.22507
    10?308 to a maximum of ?1.79769 10308.
  • Approximately 16-place precision.

double pi 3.141592653589793
53
Floating-Point Overflow and Underflow
  • What happens if we begin with the largest
    possible float and then double it?
  • What happens if we begin with the smallest
    possible positive float and divide it by 2?
  • Example
  • FloatLimitTest.cpp

54
The Character Type
  • Characters are stored as one-byte integers
    (ASCII) (see p. 850).
  • A character variable can hold any of 256
    different values.
  • Character constants must use single quotation
    marks, e.g., 'a'.

char c 'a'
55
Characters as Integers
  • Characters are interchangeable with integers in
    the range 0 to 255.
  • The numerical value of a character is its ASCII
    value.
  • Characters are ordered according to their ASCII
    values.
  • Blank space (ASCII 32)
  • Digits 0 9 (ASCII 48 57)
  • Uppercase letters A Z (ASCII 65 90)
  • Lowercase letters a z (ASCII 97 122)

56
The String Type
  • A string is stored as a sequence of characters.
  • A string may hold any number of characters,
    including none.
  • String constants must use double quotation marks,
    e.g., "Hello, world".
  • Strings are ordered lexicographically.

string s "Hello, world"
57
C Expressions
  • Lecture 5 Sep 4, 2002

58
Object Names
  • An object name must begin with a letter.
  • The name may otherwise contain any combination of
    letters, digits, and underscores (no embedded
    blanks).
  • Names are case-sensitive.
  • cost and Cost are not the same variable.

59
Object-Naming Conventions
  • The name should be meaningful.
  • The name should begin with a lowercase letter.
  • In a multi-word name
  • Begin each subsequent word with an uppercase
    letter, e.g., numberOfStudents.
  • Or, separate the words with underscores, e.g.,
    number_of_students.

60
Object Declaration
  • To declare an object, begin the statement with
    the object type, followed by the name of the
    object.
  • Declare the object only in the first occurrence.
  • The compiler reserves the appropriate number of
    bytes of memory for the objects value.
  • The objects constructor initializes the object
    (depending on the type).

61
Object Initialization
  • An object may be initialized using a constant or
    another object.

int a // Uninitialized int b 0 //
Initialized int c b // Initialized
62
Expressions
  • An expression consists of any legitimate
    combination of objects and operators
  • For example, a 2 b
  • Each expression has a value and a type.

63
Unary Operators
  • A unary operator operates on a single object.
  • Unary Operators for ints and floats
  • Negation ?
  • Increment
  • Decrement --

64
Binary Operators
  • Binary Operators for ints and floats
  • Addition
  • Subtraction ?
  • Multiplication
  • Division /
  • See page 851 for additional operators.

65
The Remainder Operator
  • The remainder operator gives the remainder when
    the left operand is divided by the right operand.
  • The remainder operator may be applied to integer
    types only.
  • Numerical examples
  • 20 3 2
  • 50 5 0
  • 3 10 3

66
Precedence
  • When two different operators are used in an
    expression, precedence tells which one is done
    first.
  • The operator with higher precedence is done
    before the operator with lower precedence.
  • See the table on p. 851.

67
Associativity
  • When the same operator is used twice in the same
    expression, associativity tells which one is done
    first.
  • Left associativity perform operations from left
    to right.
  • Right associativity perform operations from
    right to left.
  • See the table on p. 851.

68
Summary of Precedence and Associativity Rules
  • Addition and subtraction have the same
    precedence.
  • Multiplication, division, and remainder have the
    same precedence, which is higher than addition
    and subtraction.
  • These five operators are all left associative.
  • In all other cases, use parentheses to specify
    the order.

69
Sample Programs
  • IntCalcs.cpp
  • FloatCalcs.cpp
  • LbsToOzs.cpp
  • BoxCalcs.cpp
  • ReverseBoxCalcs.cpp
  • QuadraticRoots.cpp

70
Introduction to the CodeWarrior IDE
  • Laboratory 1 Sep 5, 2002

71
Mixing Types
  • Lecture 6 Sep 6, 2002

72
Promotion of Types
  • Promotion is used in expressions that contain
    objects of different types, but in the same
    family.
  • The smaller type is converted to the larger
    type with no change in value.
  • Integer promotion occurs among chars, ints,
    shorts, longs, and long longs.
  • Floating-point promotion occurs among floats,
    doubles, and long doubles.

73
Promotion of Types
  • Integer types are promoted as
  • char ? short ? int ? long ? long long.
  • Floating-point types are promoted as
  • float ? double ? long double.
  • The result is of the type of the largest object.
  • Example
  • Promotion.cpp

74
Conversion of Types
  • A type conversion occurs when objects from two
    different families of types are used in the same
    statement.
  • This typically involves a mixture of integer
    types and floating-point types.
  • The integer type is converted to a floating-point
    type.
  • The two important cases of this are
  • Mixed assignments.
  • Mixed expressions.

75
Mixed Assignments
  • A mixed assignment is an assignment statement in
    which the type of the object on the left is
    different from the type of the expression on the
    right.
  • The type of the value on the right must be
    converted to the type of the object on the left.
  • Conversion may result in a loss of precision or a
    significant change in value.
  • Conversion may not be possible, resulting in an
    error message.

76
Mixed Expressions
  • A mixed expression is an expression that includes
    objects from two different families of types.
  • This typically involves a mixture of integer
    types and floating-point types.
  • The integer-type object is converted to double.
  • The operation is performed on doubles.
  • The result is a double.

77
Type Casting
  • A conversion of the type of an expression may be
    forced by using type-casting.
  • To type-cast, write the new type in parentheses
    before the expression to be converted.

float avg (float) sum / count int feet (int)
yards / 3
78
Examples of Type Conversions
  • MixedAssignments.cpp
  • MixedExpressions.cpp
  • BattingAverage.cpp

79
Modifying Objects
  • Chapter 3

80
Input and Output and Miscellaneous Operators
  • Lecture 7 Sep 9, 2002

81
Input and Output Streams
  • Input and output use streams.
  • A stream is a mechanism that allows us to pass
    information back and forth between our program
    and the input and output devices.
  • Input streams are objects of the istream class.
  • Output streams are objects of the ostream class.

82
Buffered Input and Output
  • An input buffer is a portion of memory where the
    data typed at the keyboard are stored until the
    program is ready to read it.
  • An output buffer is a portion of memory where the
    data output by the program are stored until the
    output device is ready to receive it.
  • Unbuffered output moves directly to the output
    device, character by character.

83
Standard Input
  • Standard input refers to the keyboard.
  • Standard input is an istream object named cin.
  • Standard input is buffered.
  • The buffer contains the sequence of characters
    typed at the keyboard.
  • cin analyzes the characters in the buffer to
    determine the value of the input, according to
    the type to be read.

84
The Extraction Operator
  • gtgt is the extraction (input) operator.
  • Values may be extracted from an input stream only
    to named objects.

int a float b char c cin gtgt a gtgt b gtgt c
85
Standard Output
  • Standard output refers to the monitor.
  • Standard output is an ostream object named cout.
  • Standard output is buffered.
  • cout converts values into their character
    representations and stores the characters in the
    buffer.
  • At appropriate times, the characters are
    displayed at the monitor.

86
The Insertion Operator
  • ltlt is the insertion (output) operator.
  • Values of constants, named objects, and
    expressions my be inserted into an output stream.

int a 123 float b 4.56 char c 'x' string
s "Hello" cout ltlt a ltlt b ltlt c ltlt d ltlt endl
87
Compound Assignment Operators
  • The operator means add to.
  • The statement

x y
is equivalent to
x x y
88
Compound Assignment Operators
  • Other common compound-assignment operators

x - y x y x / y x y
89
Increment and Decrement Operators
  • To increment is to add 1.
  • To decrement is to subtract 1.
  • The increment operator is .
  • The decrement operator is --.
  • They are unary operators.
  • They may be applied only to named objects.

90
Pre- and Post-Increment
  • To pre-increment an object means to increment it
    before using it in the expression.
  • Write the operator before the object x
  • To post-increment an object means to increment it
    after using it in the expression.
  • Write the operator after the object x

91
Pre- and Post-Increment
x 3 y x z x
  • What are the values of y and z?
  • To avoid trouble
  • Use pre- rather than post-.
  • Never use them in conjunction with other
    operators.

92
Sample Programs
  • CompoundAssignment.cpp
  • Increment.cpp

93
Program Development
  • Lecture 8 Sep 11, 2002

94
Program DevelopmentStep 1
  • Decide what the input and the output will be.
  • The input tells you what information you have to
    work with.
  • The output tells you what the goal is.

95
Program DevelopmentStep 2
  • Work an example by hand.
  • Choose simple values.
  • Avoid special cases.

96
Program DevelopmentStep 3
  • Sketch the algorithm based on the example.
  • Use any convenient mixture of English syntax and
    C syntax.
  • Avoid technical issues that can be addressed
    later.

97
Program DevelopmentStep 4
  • Fill in details until it is clear how each step
    will be written in C.

98
Program DevelopmentStep 5
  • Write the program in C.
  • Once Step 4 is complete, it should be clear how
    to write the program statements.

99
Sample Programs
  • MakeChange.cpp
  • NutMix.cpp

100
Example of Program Development
  • Write a program that will compute the change
    returned on a purchase.
  • Assumptions
  • The change will be less than 1.00.
  • The change will consist of as many quarters as
    possible, then as many dimes as possible, and so
    on.

101
Step 1 Input and Output
  • The input will be the cost of the purchase and
    the amount of money given.
  • The output will be the number of quarters, dimes,
    nickels, and pennies returned in change.

102
Step 2 Work an Example
  • Let the cost be 32 and the money given be 1.00
    (100).
  • The change is 100 32 68.
  • The number of quarters is 68/25 2.
  • That leaves 68 2 25 18.
  • The number of dimes is 18/10 1.
  • That leaves 18 1 10 8.

103
Step 2 Continued
  • The number of nickels is 8/5 1.
  • That leaves 8 1 5 3.
  • The number of pennies is 3.

104
Step 3 Write the Algorithm
  • Subtract the cost from the money given to get the
    change.
  • Divide the change by 25 and truncate to get the
    number of quarters.
  • Subtract 25 times the number of quarters from the
    change to get the remaining change.

105
Step 3 Continued
  • Divide the remaining change by 10 and truncate to
    get the number of dimes.
  • Subtract 10 times the number of dimes from the
    remaining change to get the new value of the
    remaining change.
  • Divide the remaining change by 5 and truncate to
    get the number of nickels.

106
Step 3 Continued
  • Subtract 5 times the number of nickels from the
    remaining change to get the new value of the
    remaining change.
  • The remaining change is the number of pennies.

107
Step 4 Fill in the Details
  • No further detail is necessary in this example.

108
Step 5 Write the Program
  • Input the necessary values.

// Enter the cost and amount paid cout ltlt
"Enter the cost of the item " float cost
cin gtgt cost cout ltlt "Enter the amount
paid " float money cin gtgt money
109
Step 5 Continued
  • Compute the change and the number of quarters and
    dimes.

// Compute the change int change
round(100(money cost)) // Compute the number
of quarters int quarters change / 25
change change 25 quarters // Compute the
number of dimes int dimes change / 10
change change 10 dimes
110
Step 5 Continued
  • Compute the number of nickels and pennies.

// Compute the number of nickels int nickels
change / 5 change change 5
nickels // Compute the number of pennies
int pennies change
111
Step 5 Continued
  • Output the results

// Output the number of coins cout ltlt
"Quarters " ltlt quarters ltlt endl cout ltlt
"Dimes " ltlt dimes ltlt endl cout ltlt "Nickels
" ltlt nickels ltlt endl cout ltlt "Pennies "
ltlt pennies ltlt endl
112
Improvements
  • The C code can be improved somewhat.

// Compute the coins needed int change
money cost int quarters change / 25
change 25 int dimes change / 10
change 10 int nickels change / 5
int pennies change 5
113
Debugging and Testing
114
Program Debugging
  • To debug a program is to correct its errors.
  • Correct all syntax (compile-time) errors.
  • Do not use trial and error.
  • Understand each error.
  • Correct the logical (run-time) errors.
  • Insert output statements to display values of key
    variables.
  • Comment out segments of code.

115
The CodeWarrior Debugger
  • The CodeWarrior debugger allows the programmer to
  • Execute the program one statement at a time.
  • Check the values of variables during execution.
  • By comparing the actual values to the correct
    values, the programmer can pinpoint the statement
    where his program is going wrong.

116
Program Testing
  • To test a program is to demonstrate that it is
    error-free.
  • Use the worked example as test data.
  • Check the output for correctness.
  • Test special cases.
  • Be sure that every possible path in the program
    is executed.

117
Example Program Testing
  • MakeChange.cpp

118
Expression Evaluation
  • Laboratory 2 Sep 12, 2002

119
Control Constructs
  • Chapter 4

120
Boolean Algebra
  • Lecture 9 Sep 13, 2002

121
Boolean Variables
  • There are only two Boolean values
  • true
  • false
  • A Boolean variable may take on only Boolean
    values.

122
Boolean Operators
  • There are four Boolean operators
  • and
  • or
  • not
  • exclusive or (x-or)

123
Logical And
  • If p and q are Boolean expressions, then the
    expression p and q is true if and only if p is
    true and q is true.

124
Logical Or
  • If p and q are Boolean expressions, then the
    expression p or q is true if and only if p is
    true or q is true.

125
Logical Not
  • If p is a Boolean expression, then the expression
    not p is true if and only if p is false.

126
Logical X-Or
  • If p and q are Boolean expressions, then the
    expression p x-or q is true if and only if p is
    true and q is false or p is false and q is true.

127
Truth Tables
  • A truth table for a Boolean expression is a table
    that shows every possible combination of Boolean
    values of the variables, together with the
    Boolean values of the expression.
  • If there are n variables, then there are 2n
    combinations of Boolean values.

128
Example Truth Table
  • Truth Table for p and not (q or r).

129
DeMorgans Laws
  • DeMorgans Laws state that
  • not (p and q) is the same as (not p) or (not q).
  • not (p or q) is the same as (not p) and (not q).
  • DeMorgans Laws are handy for simplifying logical
    expressions without writing truth tables.
  • p or not (p and q) is the same as p or (not p) or
    (not q), which is the same as not q.

130
The Boolean Data Type
  • An object of the bool data type can take on one
    of only two bool values.
  • true
  • false
  • The bool type is in the integer family.
  • true is stored as 1.
  • false is stored as 0.
  • bool objects occupy one byte of memory.

131
The Boolean Operators
  • There are four bool operators
  • The and operator is
  • The or operator is
  • The not operator is !
  • The x-or operator is

132
Relational Operators
  • Relational operators are operators that compare
    objects.
  • Equality Operators
  • The equal to operator is
  • The not equal to operator is !
  • Order Operators
  • The greater than operators is gt
  • The less than operator is lt
  • The greater than or equal to operator is gt
  • The less than or equal to operator is lt

133
Boolean Expressions and Relational Operators
  • Typically, Boolean expressions are created by
    using relational operators to compare numerical
    or other quantities.
  • Examples
  • Integer a ! 100
  • Floating-point x lt 0
  • Character c gt 'A' c lt 'Z'
  • String answer "yes"
  • Operands may be of various types, but the result
    is always Boolean.

134
Precedence Rules
  • Precedence of operators from highest to lowest.
  • Post-increment and post-decrement , --
  • Logical not !
  • Unary operators , -
  • Pre-increment and pre-decrement , --
  • Multiplicative operators , /,
  • Additive operators , -

135
Precedence Rules Continued
  • Insertion and extraction ltlt, gtgt
  • Relational ordering operators lt, gt, lt, gt
  • Relational equality operators , !
  • Logical and operator
  • Logical or operator
  • Assignment operators , , -, , /,

136
Compound Boolean Expressions
  • Examples

x -y z ! 0 x lt y y lt z x b 0 a
/ b c !p
  • It is better to use parentheses for the sake of
    readability.

(x -y) (z ! 0) (x lt y) (y lt z) x (b
0) ((a / b c) !p)
137
Sample Program
  • BoolOperators.cpp

138
Decision Structures
  • Lecture 10 Sep 16, 2002

139
The if Statement
  • The if statement allows a programmer to decide
    whether to perform a specified action.
  • The decision is based on a Boolean expression

if (Boolean expression) Action
140
The if Statement
  • This form of the if statement makes a one-way
    decision.
  • The Action is performed if the Boolean expression
    is true. Otherwise, it is not performed.
  • In either case, execution continues with the
    first statement following the if block.

141
The if Statement
  • The Action consists of one or more C
    statements.
  • If the Action consists of exactly one statement,
    then the braces are not necessary.
  • The Action should be indented one tab stop from
    the if statement.

142
The if-else Statement
  • The if-else statement allows a programmer to
    decide which of two alternate actions to perform.

if (Boolean expression) True
action else False action
143
The if-else Statement
  • This form of the if statement makes a two-way
    decision.
  • If the Boolean expression is true, then the True
    action is performed.
  • If the Boolean expression is false, then the
    False action is performed.

144
Surveyor
  • Project 1 Sep 18, 2002

145
Surveyor
  • The problem
  • To calculate the area and perimeter of a polygon
    with five vertices, given the coordinates of the
    vertices of the polygon.

146
The Input and Output
  • The input to the program is
  • The x- and y-coordinates of the five vertices,
    expressed in feet.
  • The output from the program is
  • The perimeter of the polygon, in feet.
  • The area of the polygon, in square feet.
  • The area of the polygon, in acres.

147
Work an Example
  • Let the vertices be (1, 1), (6, 1), (6, 4),
    (4, 6), and (1, 3).

148
Work an Example
  • The distance formula produces
  • 5 3 ?8 ?18 2 17.0711.
  • The formula for the area is
  • A ½ ((x1y2 x2y1) (x5y1 x1y5)).
  • This formula produces
  • A ½ (5 18 20 6 (2)) 18.5 ft2.

149
Work an Example
  • There are 5280 feet in a mile.
  • Therefore, there are 52802 square feet in a
    square mile.
  • There are 640 acres in a square mile.
  • Therefore, 18.5 ft2 equals
  • (18.5/52802) ? 640 0.000424702 acres.

150
Write the Algorithm
  • Read the five pairs of coordinates.
  • Compute the perimeter, in feet.
  • Compute the area, in square feet.
  • Convert the area to acres.
  • Print the perimeter and the area.

151
Fill in the Details
  • Read the five pairs of coordinates.
  • Name the coordinates x1, y1, , x5, y5.
  • Read them in the order x1, y1, , x5, y5.
  • Compute the perimeter.
  • Use the distance formula for each side.
  • Use the sqrt() and pow() functions.
  • Add up the lengths of the sides.

152
Fill in the Details
  • Compute the area, in feet.
  • For the first side, compute x1y2 x2y1.
  • Compute a similar expression for each side.
  • Add up the values and divide by 2.
  • Convert the area to acres.
  • Divide the previous result by 52802.
  • Multiply by 640.
  • Print the perimeter and the area.

153
Selection Structures
  • Laboratory 3 Sep 19, 2002

154
Multi-Way Decisions
  • Lecture 11 Fri, Sep 20, 2002

155
Multi-Way Decisions
  • if statements may be nested to allow the
    programmer to make multi-way decisions.
  • The False action of each if statement is itself
    an if statement.
  • Thus, if the first Boolean expression is false,
    the program tests the second Boolean expression,
    and so on.

Multi-Way Decisions
156
Multi-Way Decisions
if (Boolean-expression-1)
True-action-1 else if (Boolean-expression-2)
True-action-2 else if
(Boolean-expression-n) True-action-n else
False-action
157
Multi-Way Decisions
  • The Boolean expressions are tested sequentially
    until one of them is found to be true, or until
    they all are found to be false.
  • When one is found to be true, its True-action is
    performed and the remainder of the structure is
    skipped.

158
Multi-Way Decisions
  • If all of the Boolean expressions are found to be
    false, then the False-action is performed.
  • The final else part is optional.
  • If the final else part is omitted and all the
    Boolean expressions are found to be false, then
    no action is performed.

159
Example of a Multi-way if Statement
  • AssignGrade.cpp
  • AssignGrade2.cpp

160
The switch Statement
  • The switch statement allows the programmer to
    make a decision based on the value of an
    integer-valued expression.
  • The value of the expression is computed. Then
    execution branches to one of several cases,
    depending on that value.

161
The switch Statement
switch (Integer-valued-expression) case
Value-1 Action-1 case
Value-2 Action-2 case
Value-n Action-n default
Default-action
162
The switch Statement
  • The Integer-valued expression must be one of the
    types bool, char, short, int, long, or long long.
  • Action-i is performed if the value matches
    Value-i.
  • The default part is optional.
  • If the value fails to match any case value, then
    the Default-action is performed.

163
The switch Statement
  • Normally, each Action ends with a break
    statement.
  • The break statement causes execution to exit the
    switch structure.
  • In the absence of a break statement, execution
    will drop through to the next Action part.

164
The switch Statement
  • The individual case actions do not require
    braces.
  • However, if any variable is declared within the
    case, then the braces are required.

165
Example of a switch Statement
  • ComputeGradeEquivalent.cpp

166
Iterative Structures while Loops
  • Lecture 12 Sep 23, 2002

167
Iterative Structures
  • An iterative structure allows a block of
    statements to be executed repeatedly.
  • The iteration continues until a specified
    condition fails, then it terminates.
  • Computers derive their computation power through
    the combination of decision structures and
    iterative structures.

168
The while Statement
  • The while statement will repeatedly execute a
    block of statements as long as a specified
    Boolean expression is true.
  • Once the Boolean expression is false, execution
    continues with the statement following the while
    loop.

169
The while Statement
while (Boolean expression) Action
  • Special situations
  • If the Boolean expression is initially false,
    then the Action is never executed.
  • If the Boolean expression is always true, then
    the loop never stop.

170
Input Loops
  • Often the purpose of a loop is to process a list
    of numbers as they are read in.
  • There are three standard ways to control such a
    loop.
  • By sentinel value.
  • By end-of-file.
  • By a counter.

171
Loops Controlled by a Sentinel Value
  • A sentinel value is a special value appended to
    the input to indicate the end of the list.
  • For example, if the data represent test scores, a
    sentinel value of 1 may be used.
  • Caution
  • The sentinel value must be a value that cannot
    occur otherwise.
  • The sentinel value should not be processed as
    regular data.

172
Loops Controlled by a Sentinel Value
  • The pattern in the loop is
  • prompt user for input
  • read input
  • test for sentinel value
  • action
  • prompt
  • read
  • test
  • action
  • etc.

173
Loops Controlled by a Sentinel Value
  • However, the test must occur at the top of the
    loop, in the while statement.
  • Therefore, the first prompt and read must come
    before the while loop.
  • The body of the while loop must follow the
    pattern action, prompt, read.

174
Loops Controlled by a Sentinel Value
const int SENTINEL Value int number Prompt
user for input cin gtgt number while (number !
SENTINEL) Action Prompt user for input
cin gtgt number
prompt
read
test
test
action
action
prompt
read
175
Detecting End of File (EOF)
  • There is an istream function eof() that returns
    true when the program attempts to read past the
    end of a file.
  • The while loop should use the Boolean expression
    !cin.eof().
  • When input is through the keyboard, there is no
    file. In this case, EOF can be simulated by
    typing CTRL-D.

176
Using the eof() Function
int number Prompt user for input cin gtgt
number while (!cin.eof()) Action
Prompt user for input cin gtgt number
prompt
read
test
test
action
action
prompt
read
177
Loops Controlled by EOF
  • When the input operator gtgt attempts to read past
    the end of a file, it returns false (0).
    Otherwise, it returns true (nonzero).
  • Thus, the expression cin gtgt Number may be used as
    the Boolean expression in a while statement.
  • This expression will both read and test the input.

178
Loops Controlled by End of File
int number Prompt user for input while (cin gtgt
number) Action Prompt user for input
prompt
read test
read test
action
prompt
179
Iterative Structures for Loops
  • Lecture 13 Sep 25, 2002

180
Loops Controlled by a Counter
  • If we know in advance the number of times a loop
    should be executed, then we can count the
    iterations and quit at the proper time.
  • Establish a counter and do the following.
  • Initialize the counter to 0.
  • Test the counter on each iteration.
  • Increment the counter.

181
Loops Controlled by a Counter
  • If the counter controls the loop, then the
    testing does not involve the input.
  • Therefore, the pattern prompt-read-test-action is
    no longer in effect.

182
Loops Controlled by a Counter
int limit cin gtgt limit int counter 0 while
(counter lt limit) Prompt user for input
cin gtgt number Action counter
initialize
test
test
prompt
prompt
read
read
action
increment
183
Combining the Methods
  • A loop may be controlled by a combination of
    methods.
  • For example, we may use a sentinel value of 1,
    but also test for EOF.
  • This loop would be controlled by both a sentinel
    value and end-of-file.

184
Combining the Methods
  • The sequence should be
  • Prompt user for input
  • Read input
  • Test input and test for EOF
  • Action
  • Prompt user for input
  • Read input
  • Test input and test for EOF
  • Action
  • And so on

185
Combining the Methods
const int SENTINEL -1 Prompt user for
input cin gtgt number while (!cin.eof() number
! SENTINEL) Action Prompt user for
input cin gtgt number
prompt
read
test
test
action
action
prompt
read
186
Combining the Methods
  • As another example, we may use a sentinel value
    of 1, but also not read more than 100 numbers.
  • This loop would be controlled by both a sentinel
    value and a counter.
  • This is trickier, as we discover when we write
    the sequence of steps.

187
Combining the Methods
  • The sequence should be
  • Initialize counter
  • Test counter
  • Prompt user for input
  • Read input
  • Test input
  • Action
  • Increment counter
  • Test counter
  • And so on

188
Combining the Methods
  • This loop requires two tests and they must occur
    at different points.
  • This is one of the rare cases where it is
    justifiable to break out of a loop prematurely.
  • Place one test in the while statement.
  • Place the other test in the body of the loop
    together with a break statement.

189
Combining the Methods
const int LIMIT 100 const int SENTINEL
-1 int counter 0 while (counter lt limit)
Prompt user for input cin gtgt number if
(number SENTINEL) break Action
counter
initialize
test counter
test counter
prompt
prompt
read
read
test input
action
increment
190
The for Statement
  • Loops controlled by counters are very common.
  • To facilitate their use, C provides a for
    statement.
  • The for statement controls the loop by
  • Initializing the counter
  • Testing the counter
  • Incrementing the counter

191
The for Statement
for (Init counter Test counter Incr counter)
Action
for (int i 0 i lt 10 i) cout ltlt "Enter
a number " cin gtgt number sum
number
192
Iteration Structures
  • Laboratory 4 Sep 26, 2002

193
Functions
  • Chapter 5

194
Functions
  • Lecture 14 Sep 27, 2002

195
Functions
  • Every function has a name
  • sqrt()
  • A function may have any number of parameters,
    including none.
  • rand()
  • sqrt(x)
  • pow(x, 2)

196
Functions
  • A function may return a value of a specified
    type. If not, then it is a void function.
  • double r sqrt(x)
  • int n round(y)
  • srand(time(0))

197
Functions
  • A function reference may be used anywhere that an
    object of its return type is permitted.
  • b a sin(angleB) / sin(angleA)
  • If a function is void, then it must be used on a
    line by itself.
  • srand(time(0))

198
Function Interfaces
  • A function interface contains
  • Exactly the information needed by the programmer
    in order to use the function.
  • Exactly the information needed by the compiler in
    order to check the usage of the function.

199
Function Interfaces
  • The function interface specifies
  • The function name
  • The return type
  • The number of parameters
  • The types of the parameters
  • The order of the parameters
  • Which parameters are constant (if any)

200
Function Interfaces
  • The method of parameter passing (value or
    reference)
  • Whether the return value is constant
  • The method of passing back the return value
    (value or reference)
  • Which parameters have default values (if any)
  • It does not specify the names of the parameters.

201
Function Prototypes
  • A function prototype is Cs method of
    specifying a function interface.
  • Examples
  • int rand(void)
  • double sqrt(double)
  • double pow(double, double)
  • void srand(unsigned int)

202
Function Prototypes
  • The function prototype must appear before the
    function is used.
  • Typically, the function prototypes are put in a
    .h file and included using include.
  • The benefit of this is that we may write the
    prototype only once (in the header file) and then
    include it in as many programs as we wish.

203
C Libraries math and cytpe
  • Lecture 15 Sep 30, 2002

204
C Libraries
  • A library is a collection of related functions
    that have been compiled and stored in a .lib
    file.
  • C provides an extensive collection of
    libraries.
  • A library file may be added to a CodeWarrior
    project and linked to a program.

205
The math Library
  • The math library contains most of the standard
    mathematical functions.
  • Include ltcmathgt in the .cpp file in which the
    functions are used.
  • A common error is to use a math function, but
    forget to include ltcmathgt.

206
The math Functions
  • double cos(double x)
  • Return cos x.
  • double sin(double x)
  • Return sin x.
  • double tan(double x)
  • Return tan x.

207
The math Functions
  • double acos(double x)
  • Return arccos x.
  • double asin(double x)
  • Return arcsin x.

208
The math Functions
  • double atan(double x)
  • Return arctan x in the range
  • ?/2 lt arctan x lt ?/2.
  • double atan2(double y, double x)
  • Return arctan y/x in the range
  • ? lt arctan y/x ?.

209
The math Functions
  • double cosh(double x)
  • Return cosh x.
  • double sinh(double x)
  • Return sinh x.
  • double tanh(double x)
  • Return tanh x.

210
The math Functions
  • double exp(double x)
  • Return ex (natural base e 2.71828...).
  • double log(double x)
  • Return ln x (natural base e 2.71828...).
  • double log10(double x)
  • Return log x (base 10).

211
The math Functions
  • double pow(double x, double y)
  • Get x raised to the y power.
  • double sqrt(double x)
  • Get the square root of x.

212
The math Functions
  • double ceil(double x)
  • Get the integer n such that n 1 lt x n
  • double floor(double x)
  • Get the integer n such that n x lt n 1.

213
Examples of Math Functions
  • FinancialPlanner.cpp
  • Surveyor1.cpp
  • Surveyor2.cpp

214
The ctype Library
  • The ctype library contains functions that
    facilitate the manipulation of characters.
  • Include ltcctypegt in the .cpp file in which the
    functions are used.
  • These functions return int because int was the
    old-style bool (0 is false, ? 0 is true).

215
The ctype Functions
  • int isalpha(int c)
  • Determine whether the specified character c is an
    uppercase or a lowercase letter.
  • int isdigit(int c)
  • Determine whether the specified character c is a
    digit.

216
The ctype Functions
  • int isupper(int c)
  • Determine whether the specified character c is an
    uppercase letter.
  • int islower(int c)
  • Determine whether the specified character c is a
    lowercase letter.

217
The ctype Functions
  • int tolower(int c)
  • Get the lowercase equivalent of the specified
    character c if c is an uppercase letter. The
    character c is returned if c is not an uppercse
    letter.
  • int toupper(int c)
  • Get the uppercase equivalent of the specified
    character c if c is a lowercase letter. The
    character c is returned if c is not a lowercase
    letter.

218
The ctype Functions
  • int isalnum(int c)
  • Determine whether the specified character c is an
    uppercase or a lowercase letter or a digit.
  • int ispunct(int c)
  • Determine whether the specified character c is a
    punctuation character.

219
The ctype Functions
  • int isspace(int c)
  • Determine whether the specified character c is
    white space (space, newline, tab, form feed).
  • int iscntrl(int c)
  • Determine whether the specified character c is a
    control character.

220
The ctype Functions
  • int isgraph(int c)
  • Determine whether the specified character c is a
    graphics character.
  • int isprint(int c)
  • Determine whether the specified character c is a
    printable character.

221
The ctype Functions
  • int isxdigit(int c)
  • Determine whether the specified character c is a
    hexadecimal digit (0 - 9, a - f, A - F).

222
Examples of ctype Functions
  • Validator.cpp

223
Flash Cards
  • Project 2 Oct 2, 2002

224
Specific Problems
  • How to control the number of problems.
  • How to select the type of problem.
  • How to create the numbers in the problem.
  • How to compute the users score.
  • How to evaluate his performance.

225
How to Control the Number of Problems
  • The user enters the number of problems that he
    wants.
  • Use a for loop to control the presentation of
    problems.

226
How to Select the Type of Problem
  • Let i be the for loop control variable.
  • Let the value of i, mod 4, represent the type of
    problem (0 , 1 -, 2 , 3 /).
  • Use a switch statement, based on i 4, to select
    the problem type.

227
How to Select the Type of Problem
  • Define symbolic constants for the cases of the
    switch statement.

const int ADDITION 0 const int SUBTRACTION
1 const int MULTIPLICATION 2 const int
DIVISION 3
228
How to Create the Numbers in the Problem
  • For addition and multiplication, use the
    expression
  • 1 rand() 10
  • For subtraction and division
  • Use the above formula to select the second
    operand and the answer.
  • Compute back to get the first operand.

229
How to Create the Numbers in the Problem
  • For example, suppose the problem is subtraction.
  • Generate two random numbers, say 6 and 9.
  • Let 6 be the second operand and 9 be the answer.
  • Compute the first operand 6 9 15.
  • Present the user with the problem
  • 15 6 ?

230
How to Compute the Users Score
  • Read the users guess.
  • Use a two-way if statement to compare it to the
    correct answer.
  • In the True action, increment a counter that
    counts the number of correct answers.
  • After the for loop is finished, use the number of
    correct answers to compute the users score.

231
How to Evaluate His Performance
  • A switch statement is inappropriate since there
    are too many possible values to check.
  • Use a multi-way if statement.
  • Each case should test a range of values.
  • The True actions should print the appropriate
    messages.

232
Using Software Libraries
  • Laboratory 5 Oct 3, 2002

233
The string Class
  • Lecture 16 Oct 4, 2002

234
String Declarations and Initialization
  • A string may be simply declared, or it may be
    declared and initialized by another string.
  • If it is not explicitly initialized, then it is
    set to the empty string.

string s // Empty string string t
Hello // Initialized
235
String Operators
  • Assignment
  • Input and output gtgt, ltlt
  • Comparison , !, lt, gt, lt, gt
Write a Comment
User Comments (0)
About PowerShow.com