Demo code: Pet and child Cat class
This demo code demonstrates how to write subclasses in C++. You do not need to know how to do this for A09. It includes:
In particular, take a look at how the three Pet accessor methods work for a Cat. getName()
is simply inherited from Pet. Pet's getOwner()
is overridden in Cat. However, because getOwner()
is not declared virtual
in Pet, this does not allow for any polymorphism. Finally, speak()
is overridden in Cat and exhibits polymorphism.
Today's Patriarche lecture: Finale
Demo code: swap.cpp and immutable.cpp
The first demonstrates a template function and the second demonstrates a template class.
Today's Patriarche lecture: 11B
Demo code: Cat class (updated).
This code demonstrates the basic syntax for defining a class. It also shows how, if your object calls new to create space for anything within its constructor, it also needs a working destructor, copy-constructor, and assignment operator function to manage those internal objects.
I split the code that we covered in lab into two versions. main.cpp can be used with either version.
In the simple version, each Cat's name is a regular string. In this case, I did not have to write the destructor, copy-constructor, or assignment function. This example shows what a simple class like Cat would normally look like.
In the dependency version, I changed Cat's name to be a string*. This means that constructing a new Cat also means creating a new "dependent" string in the heap. I think this is worse design, since I now have to write 3 more functions to properly manage the pointer to this string! Also, I added printing to all of these functions so you can see when they get called. Remember that defining these functions overrides the normal behavior; these same operations are still happening behind the scenes in the simple version.
This second version is perhaps a good example of why C++ tries to avoid pointers in general, and also why the the extra functions are needed when you have an internal pointer.
Today's Patriarche lecture: 11A
Today's Patriarche lecture: 10B
const
variables rather than #defines [more: 1, 2]
const int tree_levels = 4;
in your .hpp file instead of in your .cpp file.
void
is no longer required in the parameter lists in your function declarations/defintions.
Today's Patriarche lecture: 10A
/** * A first C++ program. */ #include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; }
[13b] - 1 Lab Point (due in today's lab; late in 14a lab):
Show me that you can compile and run a C++ "hello world" program. You may use Visual Studio, uhunix's g++, or your own laptop's software. I'll want to see your code and the output generated.
FAQ: I used to use a call a call to getchar()
to keep the output screen open when using Visual Studio. If this function is not in <iostream>, what should I use instead when writing C++ code?
Probably the simplest C++ equivalent is to use:
cin.get();
This reads a single character from the input stream and returns it. This input character can just be the enter key. (The input stream is still buffered, though, so the user can type in as much as they want before hitting enter, and cin.get()
will give you the first character entered.)
Trying to use:
char c; cin >> c;
almost works. However, by default, cin
will skip over whitespace, so this only works if a user enters at least one visible character before hitting enter.
Today's Patriarche lecture: 9C
Today's Patriarche lecture: 9B
int main(int argc, char** argv) { ... }
Today's Patriarche lecture: 9A
Today's Patriarche lecture: 8E
Today's Patriarche lecture: 8D
Today's Patriarche lecture: 8C
Demo code: fnptrbasics.c, sorting.c.
Today's Patriarche lecture: 8B
From the main page, recorded here for future reference:
A second-chance "catch up or drop out" opportunity: If you have submitted ALL assignments (A01 through A04A05) before 8am on 09 Mar, I will subtract a maximum of 20% in late penalties from each late assignment. However, if you are still missing a single assignment by that time, you will take the normal late penalties on all your assignments so far.
Today's Patriarche lecture: 7C, 8A
Mid-term evaluation results: Among other issues, one of the points raised on Tuesday was that it can be hard for some to keep up with online lectures. However, opinion was fairly evenly split on returning to a class-based format. Since the online format was originally introduced in response to past students expressing difficulty in making it to regular lecture sessions, it was decided to maintain the current format.
One compromise I considered was hosting a common lecture-viewing time in POST 126. This would provide both a structured time for those that wanted it while not denying anyone else of the flexibility of online. However, those in lab on Thursday did not express a very keen interest in this alternative. Therefore, given the momentum of the course so far, it looks like we'll stick with the established format and possibly revisit this issue next semester.
Thanks again for you feedback! If you have any additional comments on this, you can let me know by email.
Today's Patriarche lecture: 7B
Today's Patriarche lecture: 6C, 7A
Today's Patriarche lecture: 6B
Today's Patriarche lecture: 6A
[7b] - 1 Lab Point (due before 8b lab; no late):
Write a second function that prints out a TreeBall tree, as in LP6b, only this time put the root at the bottom of the screen and the leaves at the top. Attach your code and paste some sample output in an email to me.
Today's Patriarche lecture: 5C
typedef struct { struct node { char ball; VS char ball; Node* left; struct node* left; Node* right; struct node* right; }Node; };
Today's Patriarche lecture: 5B
[6b] - 1 Lab Point (due before 7b lab; late before 8b lab):
This is a continuation of 6a. It's time to implement your tree structure and write a function to print it to the screen. Since the game designers haven't decided for sure which way they want to display the tree, let's start with a function that prints the root at the top. (That'll be easier, since that's normally how we think of trees.) Write code for the following:
memset
function for this.)
* ** **** ********
* * * * * * * * * * * * * * *
* / \ / \ / \ * * / \ / \ / \ / \ * * * * / \ / \ / \ / \ * * * * * * * *
The exact nature of the connectors are up to you. (See 6a for more ideas, though those are inverted trees.)
Remember: Your tree has to be able to scale to different sizes! You should have a single #define for the number of levels in your tree. If you change only that value, your tree should gain or lose levels as appropriate.
Since we only have a few functions at this point, you can just put everything in a single .c file for now. Attach your code and paste an example of your output into the body of an email message to me.
Today's Patriarche lecture: 5A
Demo Code: arrays.c
[6a] - 1 Lab Point (due before 6b lab; no late period):
Pretend you work for a second-rate game company. They have an idea for a game where the player shoots different colored balls (say, R, G, and B) into a tree-like structure that looks something like this:
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 * B * * R * * G OR * B * * R * * G \ / \ / \ / \ / | | | | | | | | * * R G | | | | | | | | | | | | \ / \ / \ / \ / \ / \ / * * R G * B | | | | \ / \ / \ / \ / \ / \ / \ / * B * \ / \ / \ / *
The designers haven't quite decided how best to draw the text-mode tree yet. They will likely change their minds later. They're not even sure if they want to place the root at the top or at the bottom of the screen. They may also want to change the size of the tree later--possibly even within different levels of the game. That is, the tree might have 8, 16, or 32 leaves.
But the general idea is that the user will select leaf nodes and the balls will be directed towards that leaf, unless they get blocked by another ball on the way. When the user builds a trail of balls of a single color from the root to one or more leaves, that leaf node get "blown away", creating a hole at the end of that path. Future balls sent to a missing leaf then drop out of the tree. The details of scoring is still up in the air, but the general goal of the game is to eventually blow away all the nodes of the tree and then advance to the next level.
The design team wants to start play-testing some different ideas soon. Your task for this lab point is to start thinking about a program design--particularly how you would store the tree in memory? You do know that you'll always start with a perfect binary tree, though possibly of different sizes.
Answer the following questions in an email to me:
Today's Patriarche lecture: 4C
Makefile
(just makefile
works too). Note: no file extension.
target: dependency list... \t commands \t commands
make target
More on Make:
Demo code: maze-refactored 's Makefile.
[5b] - 1 Lab Point (due with A02):
Include a working makefile with your A02 submission. Each .c file should have a corresponding .o file target in your makefile. The command make all
should produce your executable file. The command make clean
should delete all the .o files.
Today's Patriarche lecture: 4B
Today's Patriarche lecture: 4A
[4b] - 1 Lab Point (due before 5a lab; late period: before 5b lab):
Closely read the following documents:
- Coding Standards
- Lab Policies, including Examples of Cheating
Then send me an email confirming that you read them. If you have any questions or comments about what you read, please state them in the email.
Today's Patriarche lecture: 3C
unsigned int binary = input; int i; for (i = sizeof(binary) * 8 - 1; i >= 0; i--) { printf("%d", (binary >> i) & 0x1U); }
int *addr
or int* addr
; array analogy)
Demo code: maze-refactored; pointerbasics.c
[4a] - 1 Lab Point (due before 4b lab):
Answer the following 5 questions in an email to me:
char letter = 'A';
I also want to use a function with the following declaration:
void manipulate(char *c);
How do I correctly call this manipulate
function to change my letter
variable?
char *letterPtr = getGrade();
I now want to see the grade I got back from the getGrade()
function. Show how to correctly print this grade as a character using printf
.
char toUpperCase(char letter) { if (letter >= 'a' && letter <= 'z') { letter -= ('a' - 'A'); } return letter; }
However, it's annoying to always have to save what it returns, as in:
char q = 'p'; q = toUpperCase(q);So I want to change this function to use pointers instead. The new function should have the following declaration:
void toUpperCase(char* letter);
Change the function definition above so it matches this new form, but still works correctly.
int main() { int a, int b; a = 3; b = 5; //swap(???, ???); printf("a = %d, b = %d \n", a, b); }
Write a swap function that will cause main to print out
a = 5, b = 3
Besides uncommenting the //swap(???, ???);
line and replacing the ???s with appropriate values, do not change any of the other code in main. Your answer should include both the swap function code and the line needed to call it.
Today's Patriarche lecture: 3B
ToDo: Read K&R Chapter 6 (first half)
Demo Code: maze.c (functions and coding stds)
Today's Patriarche lecture: 2C, 3A
ToDo: Read Chapter 5 (first half)
[3a] - 1 Lab Point (due in today's lab):
Form a group of 2 or 3 containing at least one person who completed 2b's Maze Game exercise. (Make sure your name is on your 2b code!) Learn the names of the other people in your group. Send your code to another person in your group.
Test the code that you received (or your own if your partner has no code) by answering as many of the following questions as possible:
Paste your answers--including any extra comments--into an email to me: ztomasze@hawaii.edu. Clearly mark the TOTAL score at the top of the message. Attach the code that you graded. You may show your responses to your partner and/or CC them on the email if you want to. Hit send.
[3a2] - 1 Lab Point (due before Lab 3b):
Download the following two programs:
Each of these programs contains a bug. Figure out what the programs are supposed to do, then test them to find and fix the bug.
Then, change each program from 6x6 to 7x5. Keep the # in the lower-right corner.
Test the programs again to make sure you did not introduce any new bugs.
Then, send your answers to these questions to me in an email:
For the following, answer ex, mazegame, or ~same (about the same).
For each answer, think about it a bit: why do you feel this way? (You don't have to write these thoughts here, but be ready to discuss them next lab.) Also, how did the code you reviewed/tested in lab compare to these two? What about your own code?
Update (6:15pm, 24 Jan): The original files produced warnings (for ex.c) and a couple errors (mazegame.c) in Visual Studio because I declared variables halfway through the block. I have corrected these in the file above, so those of you that use VS should be fine now. In short: the files should compile without any trouble. The bug I'm looking for in each program is a runtime/logic error (not compile time). (Sorry about that!)
Today's Patriarche lecture: 2B
[2b] - 1 Lab Point (due in today's lab):
Print a 2D box of a size that I will specify later. (So use variables for the width and height. Do not ask the user.) The box may be filled using a single repeated character and/or defined by a outer border of characters. If using a border, the dimensions given will specify the inside dimensions of the room. Examples:
4x5:
#### #### #### #### ####
6x3:
-------- | | | | | | --------
[2b continued] - 1 Lab Point (due in Lab 3a):
Place a player character in the center of your box. (This can just be on one of the center squares or else a random spot.) Also put an exit on one of the edges of the maze. Ask the user which direction to move using a letter. After each valid move, print the box/room again with the player's new position. Do not let the player leave the room except through the exit. When the player reaches the exit, end the game with a congratulatory message.
Students half-way through 111 can write this program. See here for more info.
A C detail: You still only know how to read in a single character with getchar()
. That's all you need here. (I recommend you stay away from the other input functions for now until we've covered pointers.) However, after you read in a single character, you may want to clear the rest of the characters from that line of output:
char move = getchar(); while (getchar() != '\n'); //clear input stream
Today's Patriarche lecture: 1D, 2A.
ToDo: Read Chapter 4 of K&R.
getchar()
(because we haven't talked about strings in C yet!)
[2a] - 1 Lab Point (due in Lab 2b):
Write a program that asks the user to enter a character. Then print that character value as a character, in hex, in octal, and in decimal. Space the output so that the values are always right-aligned in a single column. For example:
Enter a character: P As char: P In decimal: 80 In octal: 120 In hex: 50
+1 Lab Point: Also print the value in binary. (This will likely take some bit-shifting and a loop to do.) Example:
Enter a character: P As char: P In decimal: 80 In octal: 120 In hex: 50 As binary: 01010000
Testing: Try entering the following: a letter, a number, just hitting enter.
Today's Patriarche lecture: 1C
ToDo: Read Chapter 3 of K&R.
[1b] - 1 Lab Point: Email me a password to use for your Tamarin account by 17 Jan. Once I've created the Tamarin accounts, submit a program that just prints a message (such as "Hello World"). Your file should be named usernameA00.c
, where username is your UH username. Submit the file to Tamarin by 19 Jan.
To Do: Read Chapters 1 and 2 of K&R (Kernighan and Ritchie's The C Programming Language) over the long weekend.
Java | C |
---|---|
Released ~1995 | Released ~1973 |
Designed for embedded systems (like microwaves, smart TVs, etc); Found a home on the new WWW as applets, etc. (thanks to built-in security sandbox) | Developed hand-in-hand with Unix operating system |
Developed and centrally controlled by a corporation (Sun Microsystems, now Oracle); essentially one standard compiler (though alternatives do exist) | Many hands, ported to different hardware; many different compilers with minor differences depending on hardware platform |
7 versions released so far | Only 4 standards ("versions") in ~3x as long: 1978 - K+R's book (your textbook) 1989 - ANSI C Standard (C89) (also ISO's C90) 1999 - C99 2011 - C11 Not all of C99 is supported by many compilers yet. |
Massive API of built-in classes (GUIs, networking, etc, etc) | Very small standard library; choose between multiple third-party libraries for the rest |
Compiles to byte code (which can then be run on any system with a JVM) | Compiles directly to machine code (also called "native code", since it runs on that platform without any translation required). |
Much done automatically for you: dynamic memory allocation, garbage collection, array-bounds checking, etc. This comes with a performance overhead, though. | Most things need to be done manually be the programmer. Done incorrectly, this make subtle and terrible bugs more likely; done correctly, this leads to better-performing code. |
Built-in safety checks, such as when accessing a null object, an initialized variable, or beyond the ends of an array. When triggered, crashes the program with a helpful error message that includes the line number of the crash. | Few to no checks. May cause data corruption that leads to crash much later in a very different part of the code. When the crash does happen, no automatic error message beyond "SEGFAULT" |
Used predominately for cross-platform applications | Best suited for systems programming: device drivers, operating systems, etc. Also good for high-performance applications (such as games), especially when tweaked for a certain hardware. |