Today - PowerPoint PPT Presentation

1 / 295
About This Presentation
Title:

Today

Description:

Date bday; Date startDate, endDate; Assign values to fields in these variables ... bday.year = 1963 // 'dot' notation. Can read and write these fields as well ... – PowerPoint PPT presentation

Number of Views:130
Avg rating:3.0/5.0
Slides: 296
Provided by: davidc73
Category:
Tags: bday | today

less

Transcript and Presenter's Notes

Title: Today


1
Lecture 1
  • Today
  • start-of-semester paperwork
  • select initial groups (for two weeks)
  • review basic C
  • Reading Assignments
  • Character data type (pages 61-62, 248-257)
  • Homework
  • Make sure your accounts still work (e-mail, CoE)
  • If not, see the appropriate people

2
Course Policies
  • See syllabus for complete details
  • All materials exist on web
  • http//www.cs.ua.edu/124
  • Materials include
  • lecture notes, assignments, answer keys, etc
  • Textbook
  • same as CS 114
  • finish up what we skipped last semester

3
Course Goal
  • Finish up basic C
  • CS 114
  • sequence/selection/iteration
  • functions (including ref parameters, recursion)
  • arrays (one and two dimensional)
  • basic sorting and searching
  • CS 124
  • remainder of C data types (char, string)
  • classes
  • pointers dynamic memory allocation
  • basic data structures

4
Selection of initial groups
  • Everyone to the back of the room
  • Basic process
  • find three other people
  • find a table (cannot sit down until you have 4)
  • introduce yourselves (names, hometowns, what did
    you get for Christmas, etc.)

5
Lecture 2
  • Today
  • the character data type
  • Reading Assignments
  • More on characters (262-268, 868-869)
  • Homework
  • Make sure your accounts still work (e-mail, CoE)

6
The Character Data Type
  • A character variable holds a single character
  • char ch char x, y, z
  • ch a x x
  • char x, y, z y x
  • char five 5 z Z
  • Basic observations
  • Use single quotes with characters
  • Use double quotes with string variables (later)
  • A character variable is stored in one byte (8
    bits)

7
Relationship chars ints
  • Characters are really small (8-bit) integers
  • 8 bits gives you values in the range of 0-255
  • ASCII character set defines characters as some
    integer value in this range
  • character A 65 (ASCII representation)
  • character B 66 (ASCII representation)
  • character Z 90 (ASCII representation)
  • character a 97 (ASCII representation)
  • ASCII character table is shown on page 864

8
Can print/view chars two ways
  • As an ASCII character (default)
  • char ch
  • cin gtgt ch
  • cout ltlt You entered ltlt ch ltlt endl
  • As an integer
  • char ch
  • cin gtgt ch
  • coutltlt You entered ltlt(int) chltltendl
  • Here we cast the char as an int
  • print the integer equivalent of the ASCII
    character

9
More fun with characters
  • Since characters are really small integers, you
    can add and subtract between the two types
  • include ltiostream.hgt
  • int main( )
  • char ch 'a' Program Output
  • int a 100 197
  • a a ch f
  • cout ltlt a ltlt endl
  • ch ch 5
  • cout ltlt ch ltlt endl

10
More fun with character I/O
  • Two ways of reading in characters
  • char ch char ch
  • cin gtgt ch cin.get(ch)
  • Method on left operates in standard fashion
  • skips over white-space (spaces, tabs, new-lines)
    until it sees a character
  • Method on right grabs the next physical character
    in the input stream (whatever it is, including
    white-space)

11
Example of Character I/O
  • Data file (1 line)
  • U A C S
  • Program
  • int main( )
  • char ch1, ch2, ch3
  • cingtgt ch1 gtgt ch2 gtgt ch3
  • cout ltltch1ltltch2ltltch3
  • Results
  • output UAC
  • ch1U, ch2A, ch3C
  • Same data file
  • Program
  • int main( )
  • char ch1, ch2, ch3
  • cin.get(ch1) cin.get(ch2)
  • cin.get(ch3)
  • cout ltltch1ltltch2ltltch3
  • Results
  • output U A
  • ch1U, ch2 , ch3A

12
I/O can be a problem
  • Consider the following
  • int main( )
  • char chcout ltlt "Delete all files
    ?" cin.get(ch)
  • if (ch 'y') cout ltlt "Are you sure ?"
    cin.get(ch) if (ch ! 'n') cout ltlt
    Deleted" ltlt endl else cout ltlt Not
    deleted ltlt endlelse cout ltlt "OK
  • Output of the program
  • Delete all files ?y
  • Are you sure ?All files deleted
  • Why?
  • You entered two chars after the first prompt
  • y was the first
  • \n was the second
  • The new-line character got processed by the
    second cin.get(ch) line

13
Consider our class exercises
  • Program (revised a bit)
  • int main( )
  • char ch
  • cin.get(ch)
  • while ( ! cin.eof() )
  • cout ltlt "Entered a
  • ltlt ch ltlt " (
  • ltlt (int) ch ltlt ")
  • ltlt endl
  • cin.get(ch)
  • Run w/ two lines of data
  • Output
  • hi
  • Entered a h (104)
  • Entered a i (105)
  • Entered a
  • (10)
  • mom
  • Entered a m (109)
  • Entered a o (111)
  • Entered a m (109)
  • Entered a
  • (10)

14
Warning on character I/O
  • Windows 98 and Windows NT and Unix all use the
    ASCII character 10 for the new-line character
    (\n)
  • Some other systems (such as DOS-based and early
    Windows 95) use a two-character sequence
    (carriage-return line-feed)
  • This can impact how a program runs (or does not
    run)

15
Lecture 3
  • Today
  • finish working with characters
  • Reading Assignments
  • Structs (292-302)
  • Homework
  • Make sure your accounts still work (e-mail lab)
  • The first assignment will be given Wednesday

16
Built-in Character Functions
  • C provides a number of built-in functions that
    allow you to manipulate characters
  • listing on pages 868-869
  • Basic functions include
  • conversion between case
  • test for upper or lower case
  • test for letters (and digits and alphanumeric)
  • test for control characters
  • test for whitespace (and punctuation)
  • All require the include ltctype.hgt header

17
What are these functions?
  • int islower(char)
  • is it lowercase letter
  • int isupper(char)
  • is it uppercase letter
  • int tolower(char)
  • convert to lowercase
  • int toupper(char)
  • convert to uppercase
  • int iscntrl(char)
  • is it a control character?
  • int isalpha(char)
  • is it a letter
  • int isalnum(char)
  • is it a letter or digit
  • int isdigit(char)
  • is it a digit
  • int isspace(char)
  • is it a space, tab, newline
  • int ispunct(char)
  • is it printable but not space or alphanumeric

18
Why do functions return int?
  • Most ask a question (is it .) so it returns
    either TRUE (non-zero) or FALSE (zero)
  • Some convert between cases
  • int toupper(char) int tolower(char)
  • Consider the following
  • char ch A, ch2
  • cout ltlt tolower(ch) // outputs 97
  • cout ltlt (char) tolower(ch) // outputs a
  • cout ltlt char(tolower(ch)) // outputs a
  • ch2 tolower(ch) // assigns a to ch2

19
Arrays of characters
  • C permits you to have arrays of characters
  • normally view as strings
  • dynamic in length, special termination character
  • Can also think of fixed-length (static-size)
    arrays of characters
  • char array10 // holds ten characters
  • char array255 // holds a 5x5 matrix of chars

20
Reading an array of characters
  • Check if a ten character string is a palindrome
  • int palin(char array )
  • int a 0, b 9
  • while (altb)
  • if (arraya ! arrayb)
  • return 0
  • a a 1
  • b b - 1
  • return 1
  • include ltiostream.hgt
  • int main( )
  • char array10
  • int a, answer
  • for (a0 alt10 a)
  • cin gtgt arraya
  • answer palin(array)
  • if (answer 1)
  • cout ltlt "YES" ltlt endl
  • else
  • cout ltlt "NO" ltlt endl

21
Lecture 4
  • Today
  • struct basics
  • project one
  • Reading Assignments
  • Basics of using classes (305-310)
  • Homework
  • Project One due next Tuesday at 9pm
  • Reminder no class next Monday

22
Data Types
  • So far weve seen integers, reals, characters
  • What about other, more specialized types
  • Date contains month, day, year (3 integers)
  • Student schedule student ID, array of classes
  • Print queue array of jobs (data to print,
    priority)
  • C does not have built-in types for these
  • Can create your own representation
  • Struct look at today (briefly) old, problems
    exist
  • Class start on Friday new, improved struct

23
The struct concept
  • Some data has more than one field
  • Date month, day, year
  • Group these together (form a new data type)
  • struct Date // name of the data type
  • int month // fields in the data
  • int day
  • int year
  • // semi-colon at end is important
  • Can then use this data type in programs

24
The struct concept (continued)
  • Declare variables of this type
  • Date bday Date startDate, endDate
  • Assign values to fields in these variables
  • bday.month 4 // notice how we reference
  • bday.day 7 // the individual fields,
  • bday.year 1963 // dot notation
  • Can read and write these fields as well
  • cin gtgt bday.month gtgt bday.day gtgt bday.year
  • cout ltlt bday.month ltlt / ltlt bday.day ltlt /
  • ltlt bday.year ltlt endl

25
The struct concept (continued)
  • Can pass structs to functions
  • Can assign one struct to another
  • Date startday, endDay
  • endday startday
  • Note declare structs outside of all functions
  • include ltiostream.hgt
  • struct declarations, end each with
  • function declarations

26
Project 1
  • Project can be found at
  • http//cs.ua.edu/124/assignments/project1.htm
  • Due next Tuesday (9pm)
  • Basic word search program
  • Read in a matrix of characters (8x8)
  • Search for a four-letter word in the matrix
  • Print out matrix will all occurrences in
    upper-case
  • Only search for one word per execution
  • Watch out (Monday is a holiday)

27
Comment 1 on the Projects
  • What constitutes cheating?
  • Work in teams during class time
  • Work on projects must be done individually
  • Can discuss projects (outside of lab)
  • talk about algorithms, ideas for solving, etc.
  • should be discussions (everyone participates)
  • Cannot develop/code projects together
  • Work in lab should be done individually
  • Do not tell someone else how to do a project
  • Do not let people look at your code as a guide

28
Comment 2 on the Projects
  • Cannot expect to just go to the lab and complete
    the project in one sitting
  • studies find that effectiveness in debugging
    coding drop off dramatically after about 2 hours
  • working in the labs for long periods is
    counter-productive
  • best approach is to have something written down
    on paper before you go to the lab

29
Comment 3 on the projects
  • Information on RSI (repetitive strain injury)
  • same task over and over (e.g. keyboard use)
  • Symptoms
  • tightness, general soreness, dull ache, numbness,
    loss of strength in hands/arms
  • Web site
  • www.rsihelp.com/index.html
  • How to avoid
  • avoid long sessions
  • take frequent breaks
  • take micro-break (shift position, stretch)
  • proper position (back straight, head over
    shoulders, elbows at right angle, wrists
    straight, fingers curved)
  • type lightly
  • get plenty of rest sleep

30
Lecture 5
  • Today
  • introduction to classes
  • using C classes in a program
  • Reading Assignments
  • Basics of classes (310-320)
  • Homework
  • Project One due next Tuesday at 9pm
  • Reminder no class next Monday

31
Data Types (revisited)
  • The common definition of a data type contains two
    elements
  • a representation of the data contained in that
    type
  • a set of operations that can be performed on data
  • Built-in types have both components
  • Integers
  • 4-byte quantity, stored using 2s complement
    notation
  • operations include , -, , /, ,
  • There are some operations that are NOT defined
    for integers (convert to English, etc.)

32
Problem w/ struct for data types
  • Cannot enforce what operations get performed on
    the variable
  • Can do things to the variable that leaves the
    result meaningless
  • Date birthdate
  • birthdate.month 13 // no such month
  • birthdate.day -5 // no such day
  • Want to be able to enforce rules on what a person
    can (and cannot) do with a Date variable

33
The class construct
  • Cs new, improved version of struct
  • Allows user to define a new data type
  • Definition includes
  • how the data is physically represented
  • operations that can be performed on the data
  • this was missing with struct
  • Class construct protects the data type
  • blocks the user from individually accessing
    fields (and possibly turning them into garbage)

34
Using classes in a program
  • The person who uses a class only has to know
    the following
  • the name of the class
  • the operations that you can use on that data type
  • You do not have to know
  • how the data is stored in the program
  • how the various operations are implemented

35
Example using classes
  • Consider a class for fractions
  • called Fraction
  • You can do the following with fractions
  • Read them in (cin gtgt x)
  • Print them out (cout ltlt x)
  • Add two of them together (a b c)
  • Multiply two of them together (a b c)
  • Syntax for reading is to enter the numerator
    followed by a / followed by the denominator
  • examples 3/5 4/9 10/1

36
Consider the following program
  • int main( )
  • Fraction a, b, c // declare variables
  • cout ltlt "enter two fractions " ltlt endl
  • cin gtgt a gtgt b // read in data
  • c a b // add two fractions
  • cout ltlt "their sum is " ltlt c ltlt endl
  • c a b // multiply two fractions
  • cout ltlt "their product is " ltlt c ltlt endl

37
Classes (our goal)
  • Using classes is easy
  • Want to be able to write our own classes
  • they should look no different than any other data
    type in C
  • they should be available to other people when
    developing programs
  • having a large collection of data types should
    make developing applications easier (pick data
    types that help in your application)

38
Project Discussion Time
  • Project One is due Tuesday at 9pm
  • Time now to ask questions about it
  • Format
  • 5 minutes in group (questions that have arisen)
  • QA with entire class

39
Lecture 6
  • Today
  • The basics of classes (organization, structure)
  • Reading Assignments
  • Class methods/functions (320-327)
  • Homework
  • Project Two due next Tuesday (1/25)

40
The basics of classes
  • Class lets you define a new data type
  • Identify the data needed to represent this type
  • Identify the operations that you can perform on
    it
  • Called methods (functions)
  • Class definitions fall outside of functions
  • Visible to the entire program
  • Class definitions end with a semi-colon
  • Similar to defining a variable (or struct)

41
Sample class
  • Fractions can only declare print (no , ,
    etc.)
  • class Fraction
  • int num // data needed to represent fractions
  • int den
  • public // methods users can invoke go here
  • Fraction( ) // constructor, run when declare
    var.
  • num 0 den 1
  • void Print( ) // method to print the fraction
  • cout ltlt num ltlt / ltlt den
  • // declaration ends with semi-colon

42
Using this Fraction class
  • class Fraction // definition from previous page
  • int main( )
  • Fraction a, b, c // declare variables
  • a.Print() // print out the value of a
  • b.Print() // print out the value of b

43
Comments on classes
  • Information hiding
  • User can only see what is in public section
  • Class constructor (same name as class itself)
  • Method that is invoked when declare variables of
    this type
  • When you create a C class, you provide
  • Declaration of the class (data, methods
    available)
  • Definition of all the methods (functions)
  • Similar to declaration definition of functions
  • Can declare a class and write functions elsewhere

44
Class definition vs. declaration
  • Both (combined)
  • class Fraction
  • int num, den
  • public
  • Fraction( ) num 0 den 1
  • void Print( ) coutltltnumltlt/ltltden
  • Functions are defined (the actual code) within
    the class itself
  • Declaration
  • class Fraction
  • int num, den
  • public
  • Fraction( )
  • void Print( )
  • Definition
  • FractionFraction( ) num 0 den 1
  • void FractionPrint( ) coutltltnumltlt/ltltden

45
Project Two
  • Due Tuesday, January 25th at 9pm
  • http//cs.ua.edu/124/assignments/project2.htm
  • Overview
  • Read in an integer (non-negative)
  • Print it out using block letters
  • 124 becomes
  • 1 222 4 41 2 4 41 222 4441 2 41 222 4

46
Lecture 7
  • Today
  • Class methods
  • Reading Assignments
  • Class constructors (328-336)
  • Homework
  • Project Two due next Tuesday (1/25)

47
Creating a class (new data type)
  • First, formally declare the class
  • class Name
  • // items needed by the
  • // data type (how it is
  • // represented internally)
  • public
  • // constructor
  • // methods (functions)
  • // that users can invoke
  • // to manipulate objects
  • // of this type
  • Second, formally define all methods (functions)
    that the class utilizes
  • Can be done in the class declaration or separate
  • We will do a lot within the class itself
  • When methods get larger (more than 10 lines of
    code) it is more readable to define them
    separately

48
Sample Class (for fractions)
  • Our basic class
  • class Fraction
  • int num, den
  • public
  • Fraction( ) num 0 den 1
  • void Print( ) coutltltnumltlt/ltltden
  • Only has one method
  • Can add more (set value, add, multiply, etc)

49
Adding more methods
  • Existing method
  • Print (no args)
  • Additional methods and their arguments
  • SetNum (takes int)
  • SetDen (takes int)
  • Set (takes 2 ints)
  • MultiplyBy (take Fraction)
  • AddTo (takes Fraction)
  • First iteration
  • (next few days)
  • add these as methods with unique names
  • Second iteration
  • (about a week)
  • replace existing operators (, , , etc.)

50
Implement those Methods
  • class Fraction
  • int num, den
  • public
  • Fraction() num0 den0
  • void Print()
  • cout ltlt num ltlt '/' ltlt den
  • void SetNum(int e) num e
  • void SetDen(int e) den e
  • void Set(int a, int b)
  • num a den b
  • void MultiplyBy(Fraction f)
  • numnumf.num
  • dendenf.den
  • include ltiostream.hgt
  • int main( )
  • Fraction a, b
  • a.Set(1,4)
  • b.Set(1,5)
  • a.MultiplyBy(b)
  • a.Print()

51
Overloading Method Names
  • Recall that you could have more than one function
    with the same name.
  • What was important was the function signature
  • The number and type of the parameters passed to
    the function had to be unique
  • void myFunct(int a, int b)
  • void myFunct(char ch, double d)
  • void myFunct(int a, double ch)
  • void myFunct(int a)
  • Can do the same thing w/ methods in a class

52
Overloading methods
  • Method name is the same
  • Parameters passed to it must differ
  • Consider the MultiplyBy method
  • Might want to multiply by another fraction
    (1/41/5)
  • Might want to multiply by an integer (1/4 7)
  • Can declare two methods with the same name
  • void MultiplyBy(Fraction f)
  • num num f.num den den f.den
  • void MultiplyBy(int e) num num e

53
Lecture 8
  • Today
  • Class constructors
  • Reading Assignments
  • Class friends accessor functions (438-442)
  • Homework
  • Project Two due tomorrow at 9pm (1/25)

54
Class Constructors
  • Same name as the class itself
  • Exists in the public part of the class
  • Invoked automatically when you declare a variable
    of this type
  • Allows you the opportunity to initialize the
    variable as you see fit

55
Example
  • class Fraction
  • int num, den
  • public
  • Fraction( ) num 0 den 1
  • void Print(void) cout ltlt num ltlt '/' ltlt den
  • int main( )
  • Fraction a a.Print() cout ltlt endl
  • Fraction b, c, d d.Print() cout ltlt endl

56
Can have multiple constructors
  • class Fraction
  • int num, den
  • public
  • Fraction( ) num 0 den 1 // 1
  • Fraction(int e) num e den 1 // 2
  • Fraction(int a, int b) num a den b //
    3
  • void Print(void) cout ltlt num ltlt '/' ltlt den

57
Invoking Constructors
  • If have more than one constructor, it looks at
    the number (and type) of its arguments to
    determine which one to invoke
  • Fraction a // default constructor
  • Fraction b(5) // constructor that takes one int
  • Fraction c(3,4) // constructor that takes 2 ints
  • Fraction d5 // array, five elements, all take
  • // default constructor
  • Fraction e2 Fraction(1,2), Fraction(4)
  • // array of two items, initialized as per array
    rules

58
Know the basics of classes
  • Class data is private (users cannot access)
  • Use a constructor function to initialize the
    variable
  • User can only access variable via the methods
    (functions) defined in the public section of
    the class
  • Can write the code for the methods within the
    class declaration, or separately
  • If separate, need to indicate the scope
  • return-type classNamemethodName (args)

59
Lecture 9
  • Today
  • Friends Accessor functions
  • Reading Assignments
  • const usage (453-456)

60
Accessing data in the class
  • Users do not have direct access to the data
    within a variable from a user-defined class
  • Cannot access num den in Fraction
  • Cannot access x y in Point
  • Can provide methods (accessor methods) that allow
    the user to set these values
  • Not required
  • Allows you to do some checking on the data given

61
Accessors in Fraction class
  • class Fraction int num, den
  • publicFraction() num0 den0 void
    SetNum(int e) num e void SetDen(int e)
    if (e ! 0) den e else den 1 void
    Set(int a, int b) SetNum(a) SetDen(b)
    void Print(void) coutltltnumltlt'/'ltltden
  • int main( )
  • Fraction a a.SetNum(5) a.SetDen(3) a.Print
    ()
  • coutltltendl
  • Fraction b b.Set(5,0) b.Print()
  • cout ltlt endl

62
Friend functions
  • Methods that are part of the class itself have
    access to the variables within the class
  • The rest of the world does not have access
  • Occasionally, this can lead to non-optimal
    situations
  • Normally arises in cases where you
  • Have a preconceived notion on how to say (code)
    something
  • Are involving more than one instance of the class

63
Friend functions
  • Consider method to test if two Fractions are
    equal
  • Declare (in class) int equal(Fraction f)
  • Use Fraction a, b
  • if ( a.equal(b) )
  • This syntax is somewhat ugly, would prefer
  • Use Fraction a, b
  • if ( equal(a,b) )

64
Problem with this approach
  • This function is not a member of the class
  • Fraction a, b
  • if ( equal(a,b) )
  • Since it is not a member of the class, it cannot
    look at the private date in the class (to
    determine if the two are equal)
  • Solution make equal a friend of the class
  • Friends have access to the internals of a class

65
Example (part one)
  • Member functions only
  • class Fraction
  • public
  • int same(Fraction b)
  • if ( (num b.num) (den b.den) ) return
    1 return 0
  • Usage
  • Fraction a, b
  • if ( a.same(b) )

66
Example (part two)
  • Using a friend function
  • class Fraction
  • public
  • friend equal(Fraction, Fraction)
  • // end of Fraction class declaration
  • int equal(Fraction a, Fraction b)
  • if ( (a.num b.num) (a.den b.den) )
    return 1return 0
  • Usage
  • Fraction a, b
  • if ( equal(a,b) )

67
Lecture 10
  • Today
  • const usage
  • Two last comments on classes
  • Reading Assignments
  • Anything we have covered regarding classes that
    you have not yet read in the textbook

68
Passing parameters to methods
  • When passing a parameter to a method
  • Call-by-reference is more efficient than
    call-by-value
  • Call-by-value creates a local copy of the
    variable that is initialized to the appropriate
    value
  • Call-by-reference simply maintains a
    place-holder, as the actual changes are made to
    the variable in the calling routine
  • No big deal if you are just dealing with simple
    data types (int, double, char, etc.)
  • Can be a big deal when dealing with user-defined
    data types (that contain a lot of data)

69
Given our efficiency concerns
  • A good idea to make parameters call-by-reference
    when possible
  • Does not hurt anything
  • Can speed up execution for some data types
  • Potential problem
  • You define the interface for the classs methods
  • You have the team write the actual methods
  • People on the team do not implement the methods
    properly (dont understand C like you do)

70
Example
  • class Fraction int d2
  • publicFraction( ) d0 0 d1 1 void
    SetNum(int e) d0 e void SetDen(int e)
    d1 e void MultiplyBy(Fraction f) d0
    d0 f.d0 d1 d1 f.d1 f.d0
    0 void Print(void) cout ltlt d0 ltlt '/ ltlt
    d1
  • int main( ) Fraction a, ba.SetNum(5)a.SetDen
    (10)b.SetNum(3)b.SetDen(5)a.MultiplyBy(b)a
    .Print()cout ltlt endlb.Print()cout ltlt endl
  • // output is ??

71
Solution use const
  • Still use a reference parameter
  • Make the parameter a const (cannot change)
  • If you try and change it, compiler will flag an
    error
  • Solution to our MultiplyBy method
  • void MultiplyBy(const Fraction f)
  • d0 d0 f.d0
  • d1 d1 f.d1 f.d0 0 // this line
    would be flagged as an error

72
Another use of const
  • Consider our Print method
  • Dont want it to change the value of the Fraction
  • If implemented wrong, it could possibly do that
  • Specify the function as a const
  • Indicates it will NOT change the value of its
    calling object (error message if you try to)
  • void Print(void) const
  • cout ltlt d0 ltlt / ltlt d1

73
Comments on const
  • Must be included in method prototypes as well (if
    providing code for methods outside of class)
  • public
  • void MultiplyBy(const Fraction)
  • void Print(void) const
  • Should use const whenever possible
  • Keeps stupid mistakes from happening

74
Two more comments on classes
  • 1) Can toggle between private and public
    parts of the class as much as you want
  • class Fraction public Fraction() num0
    den1 private int numpublic Set(int a,
    int b) numa denb private int
    denpublic void Print(void) const cout ltlt
    num ltlt '/ ltlt den

75
Two more comments on classes
  • 2) Can have private methods. These methods
    can only be invoked by other methods in the
    class.
  • class Fraction
  • int num, den
  • int reduce(int a, int b)
  • // returns greatest-common-divisor of a b
  • public

76
Lecture 11
  • Today
  • Practice for exam one
  • Exam one is Friday
  • 3 tracing problems (15 each)
  • 2 coding problems (25 each)

77
Lecture 12
  • Today
  • Survey
  • More with overloading
  • Project Three assigned
  • Reading
  • Pages 458-476 (overloading)
  • Assignments
  • Project Three is due next Monday (2/14)

78
More with overloading
  • So far, we have
  • Overloaded function names
  • myFunction(int)
  • myfunction(double, char)
  • Overloaded class constructors
  • Fraction()
  • Fraction(int)
  • Fraction(int, int)
  • Overloaded class methods
  • AddTo(const Fraction a)
  • AddTo(int)

79
Overloading basic operators
  • Consider the operator
  • int a5, b10, c double a2.5, b3.1, c
  • c a b c a b
  • On the left side, works with integers
  • On the right side, works with doubles
  • We need to be able to use with Fractions
  • Fraction a(1,2), b(2,3), c
  • c a b

80
Two solutions to the problem
  • Solution 1 Overload the operator, adding
    another method to the class itself
  • Solution 2 Overload the operator as a friend
    function of the class
  • Both methods work
  • Book talks about the issue on page 442
  • Will discuss pros cons to each in future

81
Solution 1 Class Methods
  • class Fraction int num, den
  • publicFraction()Fraction(int a, int b)void
    Print(void) constFraction operator
    (const Fraction f) Fraction
    temp temp.numnumf.denf.numden
    temp.den den f.den return temp
  • int main( ) Fraction a(1,2)Fraction
    b(2,3)Fraction ccab c.Print()cout ltlt
    endlcca c.Print()cout ltlt endl
  • Note cab is
  • interpreted as
  • ca.operator(b)

82
Solution 2 Class friends
  • class Fraction int num, den
  • publicFraction()Fraction(int a, int b)void
    Print(void) constfriend Fraction operator
    (const Fraction f, const Fraction g)
  • Fraction operator (const Fraction a,
    const Fraction b) Fraction
    temptemp.num a.numb.den b.numa.den
    temp.den a.den b.denreturn temp
  • int main( ) Fraction a(1,2)Fraction
    b(2,3)Fraction cc a bc.Print()cout ltlt
    endlc c ac.Print()cout ltlt endl

83
One final comment
  • We had to overload (else would not work)
  • We did not overload operator, why?
  • Assignment (by default) simply copies all fields
    from one object (right-hand-side) to another
    object (left-hand-side)
  • This is exactly what we want to happen
  • Copies the numerator, copies the denominator
  • This can lead to problems
  • This is not always desirable, see problems later
  • Generally OK when just have simple data

84
Project Three
  • Write a class called DayTime
  • Used for time-keeping (keeps track of times)
  • A time represents the number of seconds that
    have elapsed since midnight January 1st, 1980
  • Have 2 constructors in class (write them)
  • Have methods to get and set a time object
  • Have methods to increment a time object
  • Have method to determine elapsed time between two
    objects
  • Have a main routine designed for testing

85
Lecture 13
  • Today
  • More with overloading
  • Survey results
  • Reading
  • Pages 458-476 (overloading)
  • Assignments
  • Project Three is due next Monday (2/14)

86
More with overloading
  • Goal make our data type look like built-in type
  • int a, b, c Fraction x, y, z
  • c a b z x y
  • cout ltlt c ltlt endl cout ltlt z ltlt endl
  • Last time, looked at how to overload
  • As a member function
  • ca.operator(b) which returns a new Fraction as
    its result and you can (should) write as c a
    b
  • As a friend function
  • c a b where is a friend that can
    manipulate num and den of the fractions a and b

87
Today overload input output
  • Need to write a version of ltlt and gtgt that allows
    us to read (and write) Fractions
  • Will implement this as a friend function
  • Need to look at the arguments to ltlt and gtgt
  • int a, double b int a double b
  • cout ltlt a cin gtgt a
  • cout ltlt b cin gtgt b
  • cout ltlt a ltlt b cin gtgt a gtgt b

88
What are the parameters?
  • First argument (left of ltlt or gtgt) is some I/O
    stream (cin, cout, input or output file stream)
  • This stream is changed as a result
  • Add characters to an output stream (new output)
  • Remove characters from an input stream (read
    input)
  • Second argument is the actual data item
  • Should not change when printing (const)
  • Should change when reading (not a const)
  • Parameters
  • Output (ostream os, const Fraction f)
  • Input (istream is Fraction f)

89
Overloading ltlt gtgt (first try)
  • class Fraction
  • int num, den
  • public
  • Fraction() num0 den1
  • Fraction(int a, int b)
  • numa if (b!0) denb else den1
  • friend void operator ltlt
  • (ostream os, const Fraction f)
  • void operator ltlt
  • (ostream os, const Fraction f)
  • os ltlt f.num ltlt '/' ltlt f.den
  • int main( )
  • Fraction a(1,2)
  • Fraction b(2,3)
  • cout ltlt a
  • cout ltlt b
  • cout ltlt endl
  • THIS WORKS!
  • (pretty much)

90
Problem with our solution
  • Lots of times you output multiple items at once
    (or read in multiple items at once)
  • cout ltlt the answer is ltlt a ltlt endl
  • cin gtgt length gtgt width
  • When we try and do that, we get the following
    errors
  • Fraction a(1,2), b(2,3)
  • Cout ltlt a ltlt b ltlt endl
  • No match for void ltlt Fraction
  • Candidates are operator ltlt)ostream , const

91
Consider cout ltlt a ltlt b ltlt endl
  • Process the first operation
  • cout ltlt a
  • This result should be able to be used as a
    modified version of cout for next operation
  • (cout ltlt a) ltlt b is really cout ? ltlt b
  • This result should be used as modified version of
    cout for third (last) operation
  • ((coutltlta)ltltb) ltlt endl is really cout ? ? ltlt
    endl
  • This is not what we have, our function returns
    void, not a new (modified) output stream

92
Easy solution to problem
  • Modify our return type
  • Want to return the output stream we just modified
  • What is the value of an output stream?
  • If your function is set as
  • friend ostream operator ltlt (ostream os, const
    ...)
  • System tries to get the actual value of that
    output stream, errors generated (accessing
    private data)
  • If your function is set as
  • friend ostream operator ltlt (ostream os, const
    ...)
  • Works, returns reference to new output stream

93
Overloading ltlt gtgt (correct)
  • class Fraction
  • int num, den
  • public
  • Fraction() num0 den1
  • Fraction(int a, int b)
  • numa if (b!0) denb else den1
  • friend ostream operator ltlt
  • (ostream os, const Fraction f)
  • ostream operator ltlt
  • (ostream os, const Fraction f)
  • os ltlt f.num ltlt '/' ltlt f.den return os
  • int main( )
  • Fraction a(1,2)
  • Fraction b(2,3)
  • cout ltlt a
  • ltlt b
  • ltlt endl

94
Lecture 14
  • Today
  • More with overloading
  • Reading
  • Pages 458-476 (overloading)
  • Assignments
  • Project Three is due Monday (2/14)

95
Assigning values to Fractions
  • Developed the routine Set(int, int)
  • Also have SetNum(int) and SetDen(int)
  • So much cleaner with integers and doubles
  • int x double y
  • x 234 y 2.1492
  • We need this for Fractions
  • Fraction a, b
  • a 15 a 3.5
  • b a 7 b a 2.1
  • Our existing class (pretty much) handles this

96
Our Fraction Class
  • class Fraction
  • int num, den
  • public
  • Fraction() cout ltlt "default" ltlt endl num0
    den1
  • Fraction(int a) cout ltlt "int" ltlt endl num a
    den 1
  • Fraction(int a, int b) cout ltlt "two int" ltlt
    endl numa if (b!0) denb else den1
  • friend Fraction operator (const Fraction f,
    const Fraction g)
  • friend ostream operator ltlt (ostream os, const
    Fraction f)
  • Fraction operator (const
  • Fraction a, const Fraction b) cout ltlt
    "in with " ltlt a ltlt " and " ltlt b ltlt
    endlFraction resultresult.num a.numb.den
    b.numa.denresult.den a.den
    b.denreturn result
  • ostream operator ltlt (ostream os, const
    Fraction f) os ltlt f.num ltlt '/' ltlt
    f.denreturn os

97
Run the following program
  • int main( )
  • Fraction a(1,2), b(2,3), c(3,4), d, e, f
  • d a b c
  • cout ltlt d ltlt endl
  • e d 1
  • cout ltlt e ltlt endl
  • f e 2.2
  • cout ltlt f ltlt endl
  • two int (3 of these messages)default (3 of
    these messages)in with 1/2 and 2/3defaultin
    with 7/6 and ¾default46/24intin with
    46/24 and 1/1default70/24intin with 70/24
    and 2/1default118/24

98
Actually not that strange
  • C will try and convert types to perform
    operations requested
  • Fraction Fraction int
  • Asks Can I convert an int to a Fraction?
  • Yes, we have a constructor that takes an integer
    and returns the equivalent Fraction. System
    invokes constructor to build Fraction from int.
  • What about Fraction Fraction double?
  • Yes. Can convert double to int (truncate). Can
    then convert int to Fraction (constructor).

99
What about a b c d ?
  • Modify our operator to trace execution
  • Fraction operator(const Fraction a, const
    Fraction b)
  • Fraction result
  • cout ltlt "in with " ltlt a ltlt " and " ltlt b ltlt
    endl
  • result.num a.numb.den b.numa.den
  • result.den a.den b.den
  • return result
  • Main program Output
  • Fraction a(1,2), b(2,3), c(3,4), d in with
    1/2 and 2/3
  • d a b c in with 7/6 and 3/4
  • cout ltlt d ltlt endl 46/24

100
What about a b c d?
  • This works for integers
  • int a, b, c d
  • a b c d 5
  • How do we get it to work for Fractions?
  • Do we have to do anything special? NO
  • Built-in system operator does what we need
  • Assignment operator works right-to-left
  • ( a ( b (c (d 5) ) ) )

101
Lecture 15
  • Today
  • Two last items with classes
  • Project four overview
  • Reading
  • Should now be finished with Chapter 6 and Section
    8.1 (both cover classes)
  • Assignments
  • Project Four is due next Monday (21st)
  • Exam Two is next Wednesday (23rd)

102
More with Constructors
  • Initialization Section
  • Book, pages 876-877
  • Constructor syntax
  • Constructor(args) init-section
    definition-section
  • Example
  • Fraction(int a, int b) num a den b
  • Fraction(int a, int b) num(a), den(b)
  • For our classes to date, no real difference
  • Can impact classes later on (will discuss in 325)
  • Some members (const data items) must use
    init-section

103
Copy Constructor
  • Declare a variable by making a copy of an
    existing variable.
  • Fraction a(b) // new variable a, same value as
    b
  • Fraction a b // same thing, slightly different
    syntax
  • How do you code this? (two choices)
  • Fraction(const Fraction f)
  • num f.num den f.den
  • Fraction(const Fraction f) num(f.num),
    den(f.den)

104
More on copy constructor
  • How is this different from assignment?
  • Copy constructor declares a new variable
  • Fraction a(b) // new variable a, same value as
    b
  • Fraction a b // same thing, slightly different
    syntax
  • Assignment statement assumes variables have
    already been declared
  • Fraction a, b, c // declares variables
    (constructors)
  • a b // assignment statements
  • c a

105
Project Four
  • Write a complete class
  • Complex numbers
  • Class declaration has been provided
  • You need to provide
  • Definition of all methods and friends for class
  • Main program to test your class

106
Lecture 16
  • Today
  • Basic data structures
  • Reading
  • This material is not in our textbook
  • Assignments
  • Project Four is due Monday (21st)
  • Exam Two is in one week (23rd)

107
Data Structures
  • Have spent the last few weeks looking at classes
    in C
  • Allows us to build our own data types
  • Can cleanly use these data types in programs
  • Start looking at data structures that are
    commonly used in computing applications
  • Build classes for these types

108
What are these data structures?
  • List
  • A collection of items
  • Users logged onto a system, files in a directory
  • Two special types of a list we will study
  • Stack add and remove from one end of the list
  • Used in programming languages (compiling,
    execution)
  • Queue put things on one end of list, take off
    other
  • Jobs waiting to be printed
  • Binary Tree
  • More efficient (sorts, searches, etc)

109
Data structure characteristics
  • Lists, queues, stacks, binary trees can be
    implemented in a number of ways
  • These can be classified into one of two basic
    philosophies
  • Method 1 Pre-determine the maximum size of the
    data structure, allocate space for that, assume
    you will never exceed this limit
  • Method 2 Your data structure has the ability to
    grow (dynamically) as needed to accommodate
    whatever data that you put into it.

110
Static versus Dynamic
  • Initially, we will examine all the data
    structures using static-sized data structures
  • Next, CS 124 will discuss pointers and dynamic
    memory allocation
  • Then we will revisit the data structures using
    dynamic techniques

111
Lists our first data structure
  • Want to maintain a list of things
  • Users logged into a system, files in a directory
  • Assume a maximum size for our list
  • When studying this data structure, we will assume
    a list of integers. However, it should be
    apparent that it is easy to swap this type with
    any other (Fraction, file, etc.) as needed

112
Simple List of Integers
  • Class maintains an array and a variable to keep
    track of the number in the array
  • class List int data100 // the dataint
    numElem // counter
  • publicList() numElem 0 Add(int e)
    datanumElem e friend ostream
    operatorltlt (ostream, const List)
  • ostream operatorltlt
  • (ostream os, const List x) os ltlt " "for
    (int a0altx.numElema) os ltlt x.dataa ltlt "
    " os ltlt ""return os
  • int main( ) List myListmyList.Add(5)myList.Ad
    d(10)cout ltlt myList ltlt endl

113
Closer look at our List class
  • Problems
  • How do you find an element?
  • No order, must search every element
  • How do you know if youre adding a duplicate?
  • Current method allows duplicates
  • How do you remove an element?
  • Find the element, push all elements past it
    down one slot in the array (not very efficient)

114
Improvements to our List class
  • Keep things in order (ordered list)
  • Makes it easier to find an element
  • Dont have to search entire array, just until you
    find the item or encounter an element in the list
    bigger than your item
  • Makes it easier to determine if you are adding a
    duplicate element
  • Add in order, will encounter it as part of Add
    routine
  • Worry a bit about efficiency
  • Want to find an add/remove routine that is a bit
    more efficient (dont process the entire list)

115
Our improved list class
  • Keep two arrays plus some related variables
  • To get more efficient in the time it takes to
    perform operations, we sacrifice a bit in terms
    of the space needed to store the data type
  • Keep
  • Array that has the actual data (integers) in it
  • Array that tells where to look for the next item
  • A variable that tells where the data starts
    (first)
  • A variable that tells where to add next item
    (free)

116
Example of this data
  • First 3 // first item in the list
  • Free 4 // next place to add an item
  • List is 27, 48, 52, 78, 85, 95
  • Will add the next item at location 4
  • Note list has been manipulated a bit, that is
    why it does not just start in order from the
    beginning

117
Adding to our list
  • Want to add 50
  • First 3, Free 4
  • Find appropriate spot in array (between 48 52)
  • Grab the first free item (spot 4)
  • Change 48 to point to 4 (now contains 50)
  • Change 4 to point to 52 (the 52 entry)
  • Change free to point to the next free spot (9)

118
Lecture 17
  • Today
  • Static Linked Lists
  • Assignments
  • Project Four is due Monday (21st)
  • Exam Two is next Wednesday
  • 3 tracing, 2 coding problems
  • Open Book, Open Note
  • Practice Test next Monday

119
Static Linked Lists
  • Pre-defined, fixed size to the list
  • Two arrays
  • Data the actual items in the list
  • Next subscript of the next items location in
    list
  • Two variables
  • First location of first item within the array
    (subscript)
  • Free location of next free spot in the array
    (subscript)

120
We want to write this class
  • Internal data
  • Two arrays
  • Two integer variables
  • Methods
  • Constructor (sets first, free, next array)
  • Add operation (inserts in order, no duplicates)
  • Print operation (overload ltlt operator)

121
Basic Class Declaration
  • class StaticList int data100 // the element
    in the listint next100 // location of next
    elementint first, free // subscripts
  • publicStaticList() // constructorint
    Add(int) // Add operationfriend ostream
    operatorltlt (ostream, const StaticList)

122
Constructor
  • Initially nothing in list, all elements available
  • StaticListStaticList()
  • first -1
  • free 0
  • for (int a0 alt99 a) nextaa1
  • next99-1
  • Need to set the next field so that you have a
    list of all the available slots to insert items

123
Overloading output operator
  • Want to print out the list in the format of
  • first-item second-item last-item
  • Our friend operator works as
  • ostream operatorltlt(ostream os, const
    StaticList x)
  • os ltlt " "
  • int a x.first
  • while (a ! -1)
  • os ltlt x.dataa ltlt " " ax.nexta
  • os ltlt ""
  • return os

124
Inserting new data into the list
  • Need to worry about various situations
  • List is full
  • Error cannot add this item
  • List is empty
  • Add the item
  • Must also update first appropriately
  • Adding an item before the current first item
  • Add the item
  • Must also update first appropriately
  • Adding the item anywhere past the first of the
    list
  • Add the item, update the appropriate subscripts

125
The Add routine
  • int StaticListAdd(int e) if (free -1) //
    list is full code goes here if (first -1)
    // list is empty code goes here if (e lt
    datafirst) // adding at front of list code
    goes here else add in list itself // remaining
    case

126
The Add routine (slide 2)
  • int StaticListAdd(int e) if (free -1)
    // list is full cout ltlt "Error in Add List
    is full" ltlt endl return 0 // zero indicates
    failureif (first -1) // list is empty
    code goes here if (e lt datafirst) // adding
    at front of list code goes here e
Write a Comment
User Comments (0)
About PowerShow.com