CS 120 Lecture Notes

Lecture 1

Practical Necessities

Before you can learn C++ and Computer Science in this class, learn

Lecture 2

Class Website

It is http://www2.cs.uidaho.edu/~jeffery/courses/120

Reading Assignment

Read Chapters 1-2 of Soule's textbook.

Paper Copies

If you really want a paper copy of Terence Soule's book:

Some Simple Starting Thoughts

Computers can only do 3-4 things:
  1. write a value to the screen or other output device
  2. read a value from the keyboard or other input device
  3. compute some arithmetic, like a calculator
  4. test some condition to decide what instruction to do next

NIM

NIM is an ancient and fairly simple game, with many variants.
Let's develop a version of NIM that let's you (or any human user) play against the computer. The rules for our "CS 120 variant" of NIM are simple:
  1. the game starts with a set of 23 objects,
  2. players take turns removing 1, 2, or 3 of the objects, and
  3. the player forced to remove the last object loses.
Our task is to tell the computer how to play the game of NIM. It is worth writing out an algorithm for the NIM game in English. This is a good practice to get into: both asking yourself, "How would I solve this problem without a computer?" and then using that to write out an English or pseudocode process to solve it.



Once we have done that, we can check out the first program in the text: NIM.

Lecture 3, 1/14/13

In the actual code, make sure you understand, or ask about:

This lecture we should

How did Lab #1 Go?

What needed improvement? (Not enough seats in section 2?)

Brief discussion of syntax errors

In the NIM program, what would happen if you had too many greater-than signs in an input statement, or left off a semi-colon at the end of a statement? The C++ compiler would complain. You will need to learn to read these messages and correct your program appropriately. Try some deliberate mistakes to get used to the messages and how they tell you what and where the problem is.

Tools for the Day

pretty printer (enscript, hilite.me)
compare what
enscript --color=1 -C -Ecpp -1 -o nim.ps nim.cpp
ps2pdf nim.ps
can do with what you get from hilite.me. By the way,
On Linux, file copying (cp, scp) and renaming (mv)
cp copies files (cp src dest); read its man page. scp (or scp2, or pscp if you use putty) does machine-to-machine copies (uploading and downloading files to and from wormulon) is Very important. The technology is built on "ssh" encryption protocols. Let's see a demo.
debugger (gdb)
Actually, you hardly need this tool yet, but you will soon need it, and it is the best way to "step" line-by-line through your program's execution. For now, learn to compile with -g (g++ -g nim.cpp -o nim).

Answer to a Question from Last Time

In the default emacs on wormulon:
ESC-x
let's you type an editor command by name
ESC-x shell <enter>
runs a UNIX shell inside an Emacs buffer
Control-x 2
splits the screen. Emacs can have several files open at once, and can split the screen several times. Very handy later on.
Control-x o
jumps the cursor to the "next" buffer

Some Big Ideas in Computer Science

  1. Control
    programs have a locus of execution
    a program is a set of instructions to control a computer and you have to build a model in your head of how this works
    programs execute one instruction (operator) at a time
    the order matters. operator precedence is how you control the order within expressions; usually this is within a single line. C++ control structures let you control the order of larger (usually multi-line) chunks of code
  2. Data
    memory
    data is stored in main memory or in persistent external storage (files) that can survive from one program run to the next. Almost all programs use both main memory and external storage heavily. But talking to main memory is fast and direct, and talking to external storage is slow and convoluted.
    types
    humans think: numbers versus letters, and maybe: how many of them will we need? computers add precision: how big of a number can it hold, or what alphabet are we using?
    size
    computers measure memory sizes in bytes, which are sets of 8 bits, and "machine words", which are usually (these days) 32 or 64 bits. C++'s sizeof operator reports numbers in bytes.
    lifespan
    global and local variables do not survive across program runs. But global variables live for the whole program run, locals are temporary.
  • Looking for Geek Entertainment? Check out this Map of C++
  • Academic Honesty Policy discussion
  • Text editor comparison
    NanoViEmacsNetbeans etc.CVE
    Pro easy for novices
    commands visible
    most widely deployed UNIX editor most powerful awesome nav + libraries help virtual office hours
    Con designed for email, not programming
    up to 5/24 of console wasted
    insert vs. command mode learning curve huge, not on wormulon, scp buggier than a south texas dumpster dive

    Things Learned from HW#1

    case sensitivity
    not only does it matter in C++ names, it matters in Linux scripts, such as the one I use for grading. So if I say nim.pdf, and you turnin NIM.pdf, you will lose points on subsequent assignments.
    Follow assignment specifications exactly.
    indentation
    The official required indentation style is 3 spaces per level in the code. You will get away with 2 or 4. If you don't indent for readability, in future assignments you will lose points for style.
    file types
    C++ source files have to be ASCII text. PDF files have to be in PDF format. HTML files have to be in HTML format. If you just rename a file to a different extension, you didn't do your job. You usually must run a program of some kind (e.g. a converter, or a SaveAs operation) to convert. You can check your file types on Linux with the "file" command.
    When a file gets trashed
    If your dog eats your homework, I still have to grade you. Redo your homework as fast as you reasonably can. Save copies of your work on USB jump drives. Save copies of your work on home machines. Save copies of your work on work machines. Save copies of your work in e-mails to yourself. But save copies of your work.
    Doublespaced code?
    Some pretty printers are fatter than others. Some folks turned in pretty-printed code that went as high as 6 pages on our little nim.cpp. I want you to use newlines appropriately, but do not doublespace your code.
    80 column lines, no word wrap allowed
    That's right, part of readability is: use enough newlines so that no line runs past its edge.
    80 column lines when you write output to the user of your program
    Readability applies just as much to program I/O as to source code.
    Appropriate commenting
    Comment as much as you require in order to understand yourself in 6 months. But don't comment enough for your toddler to follow what you are doing. Assume a reasonably smart C++ programmer will read your code.

    Reading

    Read Everything through Chapter 3 and Interlude 2.

    Dr. Rinker sez: Homework #1 and Lab #2 will most likely get posted later this afternoon! Check back on the web then.

    Two Techniques for Following the Locus of Execution

    hand-simulation
    Draw boxes for each variable. Then step one statement at a time.
    debugging
    Let the computer do the hand-simulation for you!

    Exercise

    Suppose you are asked to write a program from scratch to perform the following tasks: What are the first questions you should ask? What should your C++ look like?

    Class then proceeded with Quiz #1 and a hand-simulation

    Debugging

    To "debug" means to "correct" or "fix" a program that isn't working correctly. Many ways to do it:

    Following the Locus of Execution in the Debugger GDB

    More C++

    Language features we should discuss:
    reals vs. ints
    Consider the implications of this (from Wikipedia).

    Main ideas you are supposed to get:
    • computers can store 2^64 whole numbers in a 64-bit integer.
    • Floats can approximate arbitrary real numbers, with round-off error.
    floats and doubles
    For now, if you need real numbers, always use doubles, never use floats.
    magic #'s
    Don't write a 12 in your code and leave me guessing what it is. Use symbolic names for things like MONTHS_PER_YEAR.

    lecture #6

    nested if's
    You can have if statements inside if statements
    dangling else's
    Beware an else inside nested if's. Who owns it?
    short circuit AND and OR
    C++ won't bother to evaluate expressions if it doesn't have to.
    switch statements
    when too many if's are driving you nuts

    Today's C++ Concepts

    for
    loop
    perhaps even more common than while loops
    ++ and --
    increment and decrement, pre- and post- versions (x++ vs. ++x)
    runtime errors and gdb
    write a program to take an average of several numbers. Give the number of numbers first, then the individual numbers. What if number of numbers is 0?
    float type (and double)
    for approximating real numbers
    functions. prototypes. parameters.

    lecture #7

    Log Off Cleanly

    Check out the UI CS FAQ.

    Have they told ya about /x/ and X:

    The FAQ tells me that you have an extra Gigabyte out there...

    Quick Tour of C/C++ Operator List

    In case we missed any. Where do << and >> appear on this list?

    C++ Practice

    Suppose you are asked to write a program to "read in a series of numbers". (Maybe you are going to add them up, average them, or whatever). What C++ features would you need to use?

    The Great Function Lecture

    Emacs Tip

    Need to know what column you are on?

    ESC-x column-number-mode
    

    will tell emacs to show you the current column number at all times, along with the line number that it was already showing.

    Need Indentation Help ?

    Try GNU indent(1). Demo in class. I seem to prefer
    indent -bap -bbb -br -blf -bli3 -cdw -l79 -npcs -nprs -npsl
    
    which you could easily define an alias short-cut for. But I would be willing to put up with most of the available COMMON STYLES.

    A Few Rules of Floating Point and Integer Arithmetic

    Examples:

    7*9+4*5
    becomes 63+4*5, then 63+20, finally 83
    3.0/4.0*5.0
    becomes 0.75*5.0, then 3.75
    (3.0+4.0) / 5.0*2
    becomes 7.0/5.0*2, then 1.4*2, then 1.4*2.0, then 2.8

    Local Variables vs. Global Variables

    The distinction becomes important once multiple functions are used.

    lecture #8

    Parameters

    lecture #9

    Read through calc.cpp

    Trace through a sample run under gdb.

    Quiz

    lecture #10

    Welcome to Pearl Wormulon Day

    Today is our system administrator's last day at UI. What should we expect?

    Hard Copies?

    I have two hard copies of the book left in my office...was the trade-for-paper plan too onerous? If you still want hard copy, let's make a deal.

    Tips from the Quiz

    Can't have functions inside other functions
    Functions call other functions, but they cannot be declared inside other functions in C++.
    Switch statements must have {} in order make any sense.
    If you don't use { } then you don't have multiple statements to switch among, so why would you switch?
    Can't return 0 from void function
    but you can return...
    C++ features "low level logic"
    Can't easily write a condition like "if (x==2 or 3 or 5 or 7)...". If you write "if (x == (2||3||5||7))" it is legal but not what you mean. For that you have to write
     if ((x==2)||(x==3)||(x==5)||(x==7))
    
    But with a switch, you can write
     case 2: case 3: case 5: case 7:
    
    Switch statements do not test conditions
    Other than implicitly testing if an integer is == to a case. And cases must be constants.
    What do semi-colons really mean, anyhow?
    They terminate complete statements and declarations. So, its not like you just put them on the end of every line...

    Frequently Asked Questions About Function Calls and Returns

    Consider the following hypothetical piece of code:
    #include <iostream>
    using namespace std;
    void f(int);
    
    int y;
    
    int main()
    {
       int x = 6;
       y = 6;
       f(x);
       cout << "x should be 7; it is ", << x << endl;
    }
    void f(int p)
    {
       p = p+1;
    }
    
    If I asked you what was wrong, you might ask the following questions:
    Does the prototype have to include the parameter name p ?
    No, prototypes do not have to include parameter names, just types. It would be OK to follow int by p in the prototype for f, but that would be solely for human amusement.
    Does the prototype have to include the parameter name x ?
    No, f() can be called with any value of type int, not just with x. It can be called with x+5, or with 73, or whatever. The value that is passed in is copied into a new variable named p.
    Don't x and p need to be the same name?
    No, x (or any expression passed in to call f) is called an actual parameter, while the name p is called a formal parameter. During a function call, a copy of x is made and stored in p.
    Isn't p undefined, since it isn't initialized/assigned a value?
    In a function, parameters are assigned a value at the moment the function is called.
    Shouldn't f() be defined inside main() since it is called from main?
    Functions cannot be defined inside each other in C/C++. The prototype tells main() what it needs to know in order to call f(). The code body for f() can come later after main(), or before it, or even be stored in another .cpp file and linked to this file, like rand() was.
    Isn't it inconsistent to define f(int) in the prototype and f(int p) in the function definition?
    Think of prototypes as "cookie cutters" that define the shape of the function so that it can be called correctly. But additional information about the function is OK to add in the definition.
    How can f be f(x) and f(p) at the same time?
    It is f(x) at this one location where it is called, and x gets copied into p when this executes, but it executes its body with f(p) for all points in the program at which f is called. If I call f() three times:
        f(x); f(x+6); f(73);
    
    the body of f() will execute three times, with p having different values each time.
    Doesn't x need to be global?
    No, parameters transmit (copy) arbitrary expressions/values in the caller into local variables in the called function. Return statements transmit (copy) values computed in the function for use in the expression where the function is called. One way this code could be made to have f() get x's value to be 7 would be for x to be global and for f() to assign a new value to x. But global variables are uncool. Use them sparingly, like habanero sauce.
    Since we are just declaring the name of a function, couldn't the prototype just say int f(); with no parameter type?
    Prototypes have to include parameter type information. The compiler checks the type suppled in the actual parameter against the type stated in the prototype. Type must match in prototype and actual function definition too.
    This program has no cin statements, doesn't it need a cin >> x; ?
    No, it is a demonstration of calling a function. x is 6.
    Shouldn't the void f(int); be inside main's body?
    This is allowed but not required and not usual. Normal is to put prototypes at the top of a file, or in a .h file that is included at the top.
    Shouldn't f() return a value?
    void functions do not return a value. One way to fix this program would be to modify to return a value, and assign that value back to x:
       x = f(x);
    ...
       int f(int p) {
          p = p+1;
          return p;
          }
    
    There are at least two semantic errors here, one that prevents compilation and one that computes a "wrong answer". Compilation is prevented by not declaring a name x before it is used.

    lecture #11

    Reading Assignment

    In case you didn't hear it loud enough: READ CHAPTER 4.

    Tips

    What's wrong with the goto statement?
    int main()
    {
       cout << "hey" << endl;
    LABEL:
       x = get_value();
       ...
       if (t)  {
          x = x + 2;
          goto LABEL;
          }
    }
    Beware the null statement!
    Check out
          if (x == SENTINEL)
             cout << "Amazing, this is so rare!" << endl;
    
    and its cousin
          while (x < SENTINEL);
             cout << x++ << endl;
    
    return is not a function
    ...so why write it as return(x);? Clearer as
       return x;
    
    Are you sick of me asking you to indent your code yet?
    Some of the programming problems, with bogus while loops, were directly due to a student not indenting and therefore not being able to see where their curly braces were missing.
    Working on Windows, or with strange editors or IDEs?
    Carriage return characters don't seem to bug g++ but did bug pretty printers.
    Lotta impossible conditions and even some no-op statements
    if you calculate 1+x%3 the answer is from 1-3. There is no way it can be otherwise. If you execute a test, or some arithmetic on a line by itself
       x+1;
    
    it runs, but does nothing.
    Learn and use increment operators ++ and --
    They are actually faster and more readable than the alternatives.
       longwindedvariable = longwindedvariable + 1;
    
    looks better as:
       longwindedvariable++;
    
    note for adding something other than one:
       longwindedvariable += 5;
    
    Some of you have not been looking at the transcript of your session.
    If you care about your grade, keep these clean and minimal.

    Where Homeworks are Headed

    Some of you are commenting very nicely, one or two assignments have been overcommented, but many of you are not commenting much, and we will need to work on that. This assignment will have a grading point for comments.

    What you should know for this week's homework

    Adjusted Final Exam Time/Place

    We are having our final exam in common with sections 3-4. For that reason. the exam time will be Wednesday May 8 from 7-9pm in EP122 (not our regular room).

    Reading Assignment

    In case you missed it, this week you are to read Chapter 4 and Interlude 3

    The Electronic Pet

    Take a look at the Electronic Pet Program featured in Chapter 4 of Dr. Soule's text. It introduces the huge concept of object-oriented programming to the already muddy waters of C++ that we have been swimming. In addition to Dr. Soule's blow-by-blow commentary in the book, please note:

    lecture #12

    Electronic Pet, cont'd

    Late Work Policy Discussion

    On the flip side, I've had some folks requesting a "late policy" because they haven't turned in some of their homeworks or labs.

    lecture #13

    No Class on Monday

    It is Presidents Day. We love our presidents Washington and Lincoln.

    Midterm #1 on 2/21/14

    That is this coming Friday, a week from today. Wednesday February 19 will include a review.

    Wormulon Troubles

    On Header Files / Separate Compilation

    Implications:

    no #include "foo.cpp" allowed
    Actually, the above is legal but it is bad and shows you don't understand the point.
    no function bodies in .h files
    headers get prototypes and class declarations only, no code. Remember, there are exceptions to every rule, even mine.
    C++ : one header per class?
    it is OK to declare several (used together) classes in a single .h file, but your default mentality should be each class gets its .h and its .cpp

    Homework Tips

    Surfing through some CS 120 Example Programs

    Hopefully there is a big marker showing which ones use features beyond our scope thusfar in the class.

    lecture #14

    Wormulon Update

    Yup, wormulon was down a looong time on Monday. Which is to say, it was up, but was not talking to its file server.

    Supplemental Midterm Review

    4:30pm JEB 321 with Fabian Mathijssen.

    Midterm Review

    Midterm #1 covers Chapters 1-3, Chapter 4 up through section 4.4, and all interludes prior to chapter 4. What-all do you know so far?

    From Chapter 1

    What is programming?
    what is a compiler?
    What is an executable?

    From Chapter 2

    Comments
    Variables
    operators and precedence
    + - * / % < > <= >= == !=
    && ||
    types: int, double, char, string
    assignment: = += -= ++ --
    Input/output (I/O)
    cin cout << >>
    Conditionals
    if if-else
    Loops
    while do-while for
    Libraries
    #include's
    magic #'s

    From Interlude 1

    What kinds of errors can occur in a C++ program?
    What is debugging?
    What tools or techniques can you use to debug a program?

    From Chapter 3

    Functions
    Parameters
    a.k.a. arguments. Formal and actual.
    Return types; the return statement.
    Prototypes
    Function overloading
    Type Casts vs. value "promotion" and "demotion"
    Local vs. global
    Pass-by-value, or call-by-value
    Real numbers: float vs. double
    Casts
    Scope
    Switch statements

    From Interlude 2

    What is the goal of software testing?
    What kinds of things in software need to be tested?

    From Chapter 4

    Classes
    member variable a.k.a. data member a.k.a. field
    member function a.k.a. method a.k.a. operation
    private vs. public
    constructor
    Strings
    ------ no questions past here ------
    Files

    From Interlude 3

    Top-down design
    Bottom-up design

    Additional Midterm-Review materials

    lecture #15

    after the midterm exam, a class devoted to going over midterm answers ...

    lecture #16

    Points for Dots

    If on your midterm you lost one or more points for writing a "dot" product symbol instead of an asterisk...you can turn your midterm back in and I will give you that point back that I took away so cruelly. In future exams, please draw an asterisk for multiplication.

    Files

    Input

    ifstream
    a built-in standard C++ class, stands for "input file stream" where "stream" is a fancy CS word for a file (sequence of bytes).
    #include <fstream>
    necessary to declare variables of this type
    open() and close()
    In order to manipulate persistent storage, you ask the Operating System (OS). It talks to the hardware for you.
    open() can fail
    For example if the file does not exist or the name is wrong. Check for failure with fail() member function.
    any input operation (e.g. <<) can fail
    For example if the input is not of the required form. Check for failure with fail() member function, or check the value produced by evaluating the input operator or function.
    End of file is a special kind of failure.
    Check for EOF with the eof() member function. It means: there is no more input, and this is not really an error.
    The string .c_str() method
    The operating system doesn't know or care about your C++ string objects, it wants a sequence of raw bytes, i.e. a C string.
    clear()
    clear() clears any error condition from a past operation.
    ignore()
    ignore(limit, stopchar) discards (up to limit) characters until it hits a stopchar.

    Output

    ofstream
    class stands for "output stream" where "stream" is a fancy CS word for a file.
    #include <fstream>
    necessary to declare variables of this type
    open() and close()
    In order to manipulate persistent storage, you ask the OS
    open() can fail
    For example if you do not have "write" permission or disk is full. Check for failure with fail() member function.
    Append versus overwrite mode (ios_base::app)
    Optional "mode" parameter is a collection of several bits.
    formatting - IO manipulators
    setw(n) - tells stream the next output shall be at least n characters wide. Pads if shorter, does not truncate if longer. It must be passed directly to the stream object. See also: setfill(c), std::left, and std::right.
    numeric formatting
    setprecision(n) and setbase(k). dec, oct, hex.

    Discussion of File Systems

    Files have owners
    Actually, every file is owned by both a user and a "group". A UNIX group is a set of users.
    File permissions
    UNIX has separate rwx permissions for three categories of users (ugo) == 9+ bits. MS Windows originally had almost no permissions (big security hole); it has gone crazy fixing it (e.g. introducing shadow directories).
    Characteristics of filesystems on different storage media
    • maximum file name lengths vary. From 8.3 to very long.
    • drive-letters vs. mount-points
    • differences in speed in the 1000x ++
    • Links ("shortcuts"); hard and soft
    • Case sensitivity. Is case sensitivity good or bad?
    Philosophy about file naming in applications
    When should users choose file names, and when should applications just hardwire them?
    lecture #17

    Comments on Software Design

    top-down design
    take a big problem, break it into simpler pieces. Then break those pieces into simpler pieces, until you get pieces so simple that coding is easy.
    bottom-up design
    do the simple low-level pieces that you know how to do, like reading the input for example. Then figure out how to combine some of them to do something you need, until you get pieces so integrated/combined that they can do all the tasks needed by your program.
    when is something an object?
    A big part of software design is identifying what things in the application domain deserve what representation. You should write a class when you've got:
    • multiple pieces of directly related information
    • interesting things to be calculated on those pieces of information.
    Examples. Which of these deserve a class?
    • Your program has to use the price of gasoline.
    • Your program has to model a gasoline station.
    • Your program has to track the inventory of a vending machine.
    • Your program has to keep count of how many states ratify an amendment.

    Reference Parameters

    Featuring a discussion of that wacky & operator.

    Basic idea: pass a variable itself, instead of a copy
    When might this be useful?
    Syntax: & (ampersand) in a formal parameter.
    Beware ampersand's older, legacy, related use in an actual parameter.
    Reference parameters can only be passed variables
    What happens if you pass a non-variable value?
    Rest of lecture introduces the concept of arrays.

    lecture #18

    Important Facts About Arrays

    The Generic Board Game

    lecture #19

    Generic Board Game Run-through

    Introduction to Pointer Types

    We will see pointers in Chapter 6. For now:

    lecture #20

    Passing Arrays vs. Passing Objects

    #include <iostream>
    using namespace std;
    
    
    
    
    int f(int p[], int arraylen)
    {
       for(int i = 0; i < arraylen; i++)
          p[i] *= p[i];
       return p[0]+p[1]+p[2]+p[3]+p[4];
    }
    int main()
    {
       int a[5] = {1,2,3,4,5};
       int answer = f(a, 5);
       cout << " Answer " << answer
            << " middle-element " << a[2]
    	<< endl;
    }
    
    #include <iostream>
    using namespace std;
    class a {
    public:
       int u,v,w,x,y;
       a() { u=1; v=2; w=3; x=4; y=5; }
    };
    int f(a b)
    {
       b.u *= b.u; b.v *= b.v; b.w *= b.w;
       b.x *= b.x; b.y *= b.y;
       return b.u+b.v+b.w+b.x+b.y;
    }
    int main()
    {
       a aa;
       int answer = f(aa);
       cout << " Answer " << answer
            << " middle-element " << aa.w
    	<< endl;
    }
    

    Lessons from these fine programs:

    Introduction to Algorithmic Complexity

    Differing Resources Requirements: Examples

    Suppose you have a problem such as: to read in a sequence of integers from a file, and store them in an array. How much time or space will it take?








    Hopefully you know that "within reason", the amount of time and space ought to be proportional to the amount of input data.

    int n;
    count << "How many? ";
    cin >> n;
    int a[n];
    for (int i=0; i<n; i++)
       cin >> a[i];
    

    The rest of this discussion focuses on time. Proportional to input size (n) means literally: n comparisons, n inputs, n increments. If the work per element (1 compare, 1 input, 1 increment) adds up to some time c, our total time is cn, a co-efficient constant times the number of times around the loop.

    Here is another example: how much time will it take to determine whether all n integers are sorted in ascending order?

    boolean is_ascending(int a[], int n)
    {
       for (int i=0; i<n-1; i++)
          if (a[i]>a[i+1]) return 0;
       return 1;
    }
    
    The time is: you guessed it, proportional to n. But this problem doesn't always take n. In the best case, it returns on the first "if". On the average case (if the data is random) it takes far, far less than n to figure out that the answer is false. In the worst case it takes n.

    Here's a tougher one: how much time will it take to determine whether any of the numbers are duplicates?

    boolean is_unique(int a[], int n)
    {
       for (int i=0; i<n; i++)
          for (int j = 0; j<i; j++)
             if (a[i] == a[j]) return 0;
       return 1;
    }
    
    This is n times... something. n times we do another loop. The other loop goes i times, but i is bounded by n and averages n/2. The total number of times through the for-loops is n*n/2 or n2/2.

    Big-O Notation

    The notation for characterizing how the time or space resources in an algorithm scales is called Big-O notation. lecture #21

    Interlude 4

    In some later CS classes, you may need to be proficient with C++'s predecessor, the C language.

    struct types

    A struct is a class with all public member variables and no member functions. The notion of defining the struct is separate from the notion of defining the type name.

    C I/O

    C uses an arguably more pleasant, theoretically less-efficient I/O model.

    Arrays of char

    Some (C++) stuff you may need to know

    Every time you pass an object as a parameter, you make a copy.
    Sometimes this is harmless, sometimes it will trigger a crash.
    Example "good" use of this property
    arrays are always passed by reference. If you need to pass an array by value (i.e. copy when passing it into a function) you could place the array in a class, and pass the class instance.
    Files (ifstream/ofstream) are examples of objects that it is unwise/unsafe to copy.
    So pass them by reference.
    Function Overloading
    The parameters' number and/or types must be different, so that the compiler can tell which one to use. Beware types that auto-promote.
    Parameter Defaults
    As in this nice Microsoft technical note.
    lecture #22

    Short Introduction to Multi-Dimension Arrays

    int A[6][7];
    
    See array.cpp for a short example. lecture #23

    Reading Assignment

    Read chapter 6 on the robot world application if you have not done so yet.

    RobotWorld

    lecture #24

    From Chapter 6

    User-defined "libraries"
    What Dr. Soule refers to as libraries are generally referred to as "modules". A real "library" is in a special file format that contains a collection of .o files.
    Two kinds of real libraries
    "static libraries" are copied into the executable. "dynamic libraries" are loaded once and shared by (possibly many) programs.
    Library file names
    Vary by platform, (Linux .a/.so; Windows .lib/.dll; Mac .a/.dylib)
    Separate compilation
    Let's do a linking of multiple .o files example, and a quick (re?)demonstration of makefiles.
    In-line functions
    If you stick the code body into the class definition, the body of the code may get copied in place of every call to that function. What are the pros and cons?
    Two-dimensional arrays redux
    Your homework requires 2D arrays in spades.

    Pointers, part 2

    What is the point of pointers?
    Compare *p and ->
    It turns out pointers to objects (and in C, structs) are common. Very common. So common that programs would start to be filled with calls like
     (*op).f(); 
    The * followed by . pattern was recognized early on as being so common that it got its own, more readable operator:
     op->f(); 
    Array-Pointer equivalence
    (The name of) an array is a (constant) pointer to the 0th element of the array. You can use a pointer as an array. We should think a bit about what that means.
    Pointer arithmetic
    p+5 is equivalent to &(p[5]). Adding an integer to a pointer adds (integer * elementsize) to the address.

    lecture #25

    Midterm #2: April 11.

    We will have a review on April 9.

    Command Line Arguments

    More with Pointers

    Pointers are primarily useful in the following ways: Let's do examples of the first three of these. Chapter 6 also discusses new and delete which are Very important. Are you ready for Wednesday's quiz?

    Array-growing example

    Commentary: lecture #26

    This lecture on base conversions and two's complement arithmetic is provided courtesy of Dr. Rinker.

    Number Systems

    A number in base B of the form
       (IJKL)B
    
    can be evaluated in the following way:
    L * B0 + K * B1 + J * B2 + I * B3
    

    DecimalBinaryOctalHexadecimal
    000000000x00
    100001010x01
    200010020x02
    300011030x03
    400100040x04
    500101050x05
    600110060x06
    700111070x07
    801000100x08
    901001110x09
    1001010120x0A
    1101011130x0B
    1201100140x0C
    1301101150x0D
    1401110160x0E
    1501111170x0F
    1610000200x10

    Binary to Decimal Conversion

    Example: Convert (1101)2 to Decimal
    1101 = 1 * 23 + 1 * 22 + 0 * 21 + 1 * 20
         = 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1
         = 8 + 4 + 0 + 1
         = 13 a.k.a. (13)10
    

    Hexadecimal to Decimal Conversion

    Example: Convert (E42)16 to Decimal

    E42 = E * 162 + 4 * 161 + 2 * 160
        = 14 * 256 + 4 * 16 + 2 * 1
        = 3584 + 64 + 2
        = 3650
    

    Decimal to Binary Conversion

    Example -- Convert (25)10 to Binary.

    Method: divide by two repeatedly until you get to 0. Each division by 2 computes one bit (the remainder).
    Quotient Remainder Accumulated Bits
    25/2 12 1 1
    12/2 6 0 01
    6/2 3 0 001
    3/2 1 1 1001
    1/2 0 1 11001

    Decimal to Hex Conversion

    Example: Convert (79)10 to Hexadecimal

    Method: divide by 16 repeatedly until you get to 0. Each division by 16 computes one hex digit (the remainder).
    Quotient Remainder Accumulated Hex Digits
    79/16 4 15 F
    4/16 0 4 4F

    Binary to Hex Conversion

    Example: Convert (10101110)2 to Hex

    Method: every four bits of binary is exactly 1 hex digit. Convert each four bits to decimal and then map to hex.
    binary 1010 1110
    decimal 10 14
    hex A E
    answer AE

    Hex to Binary Conversion

    Example: Convert (3B7)16 to Binary

    Method: every hex digit is exactly four bits of binary. Convert each hex digit to its decimal equivalent if you need to, but then use it to fill out a four-bit binary value.
    initial hex value 3B7
    hex 3 B 7
    decimal 3 11 7
    binary 0011 1011 0111
    answer 001110110111

    The Problem with Sign-Magnitude Notation

    Why is Sign-Magnitude a Pain?

    Probably due to rule #3 below.
    1. If both numbers are positive, add them and prepend a 0.
    2. If both numbers are negative, add them and prepend a 1.
    3. If one is positive and one negative, determine which has a larger absolute value. Subtract the smaller from the larger. Prepend a 0 or a 1 depending on which one was larger.

    One's Complement Representation

    But +0 and -0 are generally considered the same number, and 0 is used heavily in computer programs. Having two representations for the same number is a bad idea...

    One's Complement to Decimal

    Positive one's complement numbers have standard binary interpretation. Negative one's complement numbers are converted to decimal by flipping all bits and the converting the binary to decimal.
    number its decimal
    00101101 45
    11101101 -(00010010), or -18
    11111110 -(00000001), or -1
    "Finding the One's Complement" of a number means finding the negative of a number. It is easy-peasy, just flip all bits.
    number its one's complement
    00101101 11010010
    11101101 00010010

    Two's Complement Representation

    Two's complement has only one 0! How handy.

    Finding the two's complement