Thursday, December 2, 2010

An update in few months...


Haven't posted in a while due to schoolwork - simply can't go to sleep
tonight. As of December 2010, I've decided to try taking advanced
programming class again amd trying to review what I learned in calculus for
the last few weeks. As a result, I've almost neglected sharing more C++
posts - once finals are over, I plan to continue from where I left off -
stacks, heaps, implicit "this" variable and continue on to talking about
inheritance before diving to data structures. Speak of that sequence, the
last topic will be one the rule of big three - destructor, copy constructor
and the assignment operator and its relationship with pointers.

As of now, I plan to start exploring data structures with reviewing C++ and
a few more prep materials such as algorithms and recursion. Then, I plan to
start talking about linked lists, stacks, queues and trees - while
introducing useful algorithms that works with data.

That's all...
//JL P.S. Found the blog of my former "employer/teacher" at LAUSD - congrats
to a fellow marshall student for winning an Apex...

Thursday, September 16, 2010

C++: What if I want to point to more than one item?

At least the formatting would be okay this time... Thanks to a consultant's
suggestion, I've changed the formatting a bit.

As we've seen, pointers are used to hold the address of a variable to which
it points to. This has one problem though: what if we want to work with more
than one item at a time? To help out with this task, we can use dynamic
memory - a memory that is allocted at runt time. Also, to traverse a set of
items, we can employ memory arithmetic - moving from one item to next
depending on number of bytes that a given item occupies in RAM.

Let's come back to our basic "car" class - where we have model, manufactured
year and company name as member variables. Suppose if you are a Nissan
dealer who needs someone to print a list of Nissans available, and suppose
there are five cars left after a busy day of sale. The programmer (me, in
this case), is thinking of employing pointers to point to Nissan car
objects, but is wondering how to store five cars and have the pointer point
to it.

To help me out, what would be your suggestion? As it turns out, after
noticing that all Nissans share a common attribute - that they are cars -
allows me to employ a dynamic array of cars to help me print out what cars
we have left at our dealership. So, I started to write...

Car * car_ptr = new Car[5];

Remember a similar code from last time? We've just declared a dynamic array
of five cars. The keyword "new" means that we wish to use dynamic memory
(stored on the heap, as opposed to stack, which holds static variables; I'll
come back to it in a second). Just like arrays, we use brackets ([]) to tell
the computer how many items we would like to use - so that we can use index
0 through 4. This is one form of declaring a collection of dynamic memory.
Note that the pointer would point to the first of these elements (index

But if your goal is to declare just one item and put it in dynamic memory,
we could employ new keyword as follows: Suppose if I have a character called
"C" that I'd like to put it up on dynamic memory, and have a character
pointer point to it. We can write it as follows:

char * char_ptr = new char)"C"); // Hope my syntax was correct...

Or, suppose if I have a double called "3.0" and wish to stored it on dynamic
memory, we can do this:

double * double_ptr = new double(3.0); // I think this is better.

The above two lines just declares a pointer to point to an item on the
dynamic memory (only one item, not an array of items). As you'll learn
later, if you forget about your declaration, a troubling consequence may
occur - especially if you've declared a dynamic array.

Now back to the dealership. What if I want to assign a particular car model
to a specific index? We can use memory arithmetic to help us with this task.
When this is invoked, moving from one item to next is dictated by how many
bytes does a given object use in memory. Common sizes are 4 bytes for an
integer, 8 bytes for a double and 1 byte for characters (strings is a
special case, as it is an array of characters). For example, if I have four
integers (starting at address 100), if I use memory arithmetic, index 1 of
this array would get the address 104, index 2 at 108 and index 3 at 112.

But counting bytes in memory is very tedious (note that RAM addresses are
expressed in hexadecimal numbers - base 16). To make coding faster, we use
subscript operator ([]) to help out with this task. All we need to access a
given item in a set of items is via its index location. For instance, if I
want to access the second car in an array of dynamic cars, we'd write:

Car_ptr[1] = whatever; // remember our discussion on zero-based indexing.

So, the problem of assigning a car model in an item in our car array has
been fixed - and even allowing me to assign the same car model to all of
them has been fixed via for loop, as shown below (pseudo code first, then
C++ code):

Pseudo code:
1. First, find out how many cars are there. Here, we don't need to do that,
since we do know how many there are (5).
2. Use for loop to assign these car objects to the same manufacturer, model
and manufactured year. We would use subscript operator to assign items in
the car object to same values.

In C++, we'd get:

For (int i = 0; i < 5; i++)
Car Nissan (2008, "Nissan", "Ultima");
Car_ptr[i] = Nissan;
} // If I remember right.

At least, three quarters of my job is done. The only thing left is printing
it: same principle as assignment code above.

For (int i = 0; i < 5; i++)

Ah, yes, I should have gone over the arrow operator. Whenever we access data
that a pointer points to (including member functions), we use arrows (->)
instead of dot (.) operator. For instance, if we have a table class and want
to print its length (given if length variable (an integer) is declared in
there), we'd write:

Table test (3, 5); // Length = 3, height = 5.
Table * test_ptr = &test; // The address of our test table.
Cout << test_ptr->length; // Print the length of this table that the pointer
is pointing at.

Look at the last line. Instead of the above line, the compiler would give an
error if you write:

Cout << test_ptr.length; // Uh oh...

Thus, whenever we work with pointers that needs to access data (for our
classes), we'd use arrows.

One last bit: What if you forget about assigning dynamic pointers and let
the program terminate? The next time you run a program, there might not be
any more room for you to work with data. This is the consequence of memory
leak where a program would forget to deallocate (remove, well, almost)
memory when it is done. To help avoid this problem, we'd use "delete"
operator to return memory locations that we've used back to the operating

Depending on the memory we've used, there are two ways that relies on
presence of subscript operator:
* If you used only one dynamic variable, it is sufficient to write:
delete dynamic_ptr;
* If you've used a dynamic array, then it is CRUCIAL to put subscript
operator, otherwise only the first of these items (index 0) will be
deallocated, leaving the rest of the array "floating around":
Delete [] array_ptr;

So, to clean up our dealership and other dynamic variables we've used, I'd

delete [] car_ptr; // Forgetting the subscript operator produces memory
Delete double_ptr; // Only one double was used.
Delete test_ptr; // Only one test table.
Delete char_ptr; // Only one character.

I think that's all I can think of in terms of memory allocation (mostly
dealing with dynamic memory allocation) and memory arithmetic. Next time,
I'll discuss the self-assignment (this->) operator, as well as more on stack
versus heap.
// JL

Sunday, September 12, 2010

C++: Pointer exercise 1

Before I dive into rants on memory allocation, I thought I should pose a
small challenge for you - to make sure that you haven't forgotten about
working with basic classes:
This exercise is divided into two parts:
1. Create a computer class to store two string variables (company name and
model), as well as a double for storing CPU speed (in gigahertz (GHz). The
default constructor would set the computer model and brand name to null
string and CPU speed to 0. The parameterized constructor would assign
variables data from user-supplied arguments. That's it for now.
2. Create a computer variable named "my_computer" and a computer pointer
called "computer_ptr" that'll point to the address of my_computer. Then
create another computer object called "Apple", this time assign it the name
"Apple (brand name) Mac Book Pro (model)" and set the CPU to 2.13 GHz. Then
assign a new computer pointer called "Apple_ptr" to our Apple computer
object. Then assign computer_ptr pointer so that it now points to apple_ptr.
We'll revisit our Apple notebook later when discussing about displaying it
as part of a computer store shelf i.e. memory arithmetic and how to use
this-> operator.
// JL

C++: Declaring pointers

Last time we examined what a pointer is and a basic declaration of a pointer
- address of a variable. Let's discuss other ways of declaring pointers.
Along the way, I'll introduce you to memory arithmetic (especially in
regards to the last method of pointer declaration).
There are four or five ways of declaring a pointer (remember that in order
to declare a pointer, it needs the asterisk operator between the ptr name
and the data type). The first way is, of course, declaring the pointer to
hold the address of a known variable. For instance, if I store my age in an
integer variable and have an age pointer point to my age variable, I'd
int age = 20;
int * age_ptr = &age;
Sound familiar? This is exactly the same declaration style I've used on
previous post, except that I'm now using integer pointer (as I've said
earlier, pointers can point to anything). Just like last time, the "age"
variable would hold my age right now (20) with age_ptr holding the address
where my age variable lives (not exactly "lives," but more towards
"located."). So, if we verify my age using cout, it'd be (like last time):
cout << *age_ptr << endl;
Remember what we've discussed earlier - just saying "age_ptr" would give us
the address of something, not the actual guy, thus I wrote dereference
operator along with age_ptr. On the monitor, my age (20) would be displayed.
But suppose if I have a friend who wish to store his age as a pointer and my
current age_ptr be modified (reassigned) to point to his age pointer? The
answer is perfect "yes." Pointers can point to other pointers, just like
values from one variable can be assigned to another. Let's see how we can do
int friend_age = 24;
int * friend_age_ptr = &friend_age;
Here's the tricky part:
my-age_ptr = friend_age_ptr;
Wow, something we haven't seen before, but once you examine it carefully,
you'd understand that the above statement is perfectly valid. To help us
with a better illustration, suppose the address of my_age variable was 0001
and my friend's age variable address was 0002. Here's the map of the
variable assignment:
* my_age_ptr was initially assign to address 0001 (my age).
* Then friend_age_ptr was assigned to address 0002 (my friend's age).
* using the above map, we reassigned my-age_ptr to point to friend_age_ptr -
the address pointed to be my_age_ptr was changed from 0001 to 0002.
Now, if we print my_age_ptr (via dereference operator), we'd get my friend's
age instead (by the way, that friend of mine is my programming consultant).
But what if we have a pointer but don't know the variable to which it should
point to? In this situation (particularly when writing class constructor and
if part of the encapsulated variable is a pointer), then we can use a
safeguard - assigning the pointer to the address of zero (or null). A
typical declaration is:
data_type * pointer = NULL; // (notice that we need to capitalize the word
This is useful if you need to create a known pointer but doesn't know where
it should point to, or when creating default constructor for a class that
has a pointer variable as part of encapsulated data. But this declaration
has a cost: a likelyhood of a "fight" between you and your computer over not
being able to read from address of zero (one form of segmentation fault;
I'll come back to it in more details later). In order to avoid this, be sure
to assign a valid variable address to the pointer once the variable was
declared, like this:
double * double_ptr = NULL;
cout << *double_ptr << endl; // BAAAAAAD!
// Computer says, "Hey, you can't read from address of zero!".
double cosine_30_dg = 0.866; // Cos 30 = sqrt(3/2).
double_ptr = &cosine_30_dg;
cout *double_ptr << endl; // Thanks.
Now, when we print this, it shows 0.866 (cosine of 30 degrees, which, when
squared and multiplied by square of sine of 30, produces 1 (a well known
trig identity)).
The last method is something I need to come back in full detail later, as it
is related to the next post on memory management and dynamic memory, but
just want to show you how it can be done:
Suppose if I have a collection of data (like a vector) and want to store it
somewhere but don't want to bother with creating another variable just to
hold this collection. A neat way of accomplishing this task is using
so-called "dynamic memory" where we can work with it at run time. Unlike
so-callee variables we have worked with, this memory requires special
attention, as doing wrong things at wrong time could result in this memory
not being usable by other programs (called memory leak where a program would
use more and more memory but not relinquish memory space that it no longer
needs). Also, this memory does not have a name (actually, a variable name
does exist, but it is not that apparent yet).
To work with dynamic memory, we need pointers and two new keywords - new and
delete. I'll come back to meaning of these keywords in a sec (perhaps next
time), but to give you an idea of coding it, let's create a pointer that
stores five dynamic integers i.e. dynamic memory of five integers:
int * dynamic_ptr = new int[5];
Almost similar to how we'd declare an array of something as we've seen
earlier. Here, the pointer (dynamic_ptr) points to index 0 (first number) of
our array.
To tell the computer that we don't need this dynamic array anymore, we'd
delete [] dynamic_ptr;
Note that we use brackets ([]) to delete the entire array. We'll examine the
operation of this task in more detail as we continue our pointer discussion
with dynamic memory allocation (coming up shortly), but a bit of review
exercise is in order...
// JL

Friday, September 3, 2010

C++: Pointers - Hey, where do you live at?

I know you were caught off guard at this question... Well, the next few
topics will help you understand what I mean by this question.
For starters, I thought I should point out where I actually live and the
address of my school (UC Riverside) before diving into C++ equivalent.
Geographically speaking, I live in Koreatown in Los Angeles - yes, where
people like myself live. My apartment is few blocks away from Staples Center
(I am a Lakers fan). Some of the attractions near my address include
downtown L.A., Convention Center, Koreatown Galleria and so forth.
Now to my school. My school is located just east of downtown Riverside
(right by the CA State route 60). Actually, State Route 60 divides the
campus between eastern and western halves. The address is 900 University
Ave. Riverside, CA 92507.
Now to the subject at hand: Do you know how to say, "tell me the address of
UCR" in C++? Can you say, "what exactly is at 900 University Ave." at
Riverside in C++ terms? The answer to these questions is a perfect "yes."
C++ does allow programmers to find out what is stored at such and such
memory address - called pointers. A pointer is the memory address of
something e.g. an integer, a string, or to a small table class we've seen
before. Each address stores the location of where a given data lives, and in
case of arrays and vectors, the address of first of this series of items.
This is done through two operators - the 'address of' and
"pointer/dereference" operators (& and *, respectively).
For instance, suppose if I say, "tell me the address of my school and store
it in a string pointer," I'd write:
string school = "UC Riverside";
string * school_ptr = &school;
Quite a few new things... In essence, these two lines are almost identical
to when we declare variables. The first line is obvious: store "UC
Riverside" in a string variable called "school". The key is the line after
that declaration: store the address of the "school" variable in a pointer
called "school_ptr." Whenever one write a star (asterisk) between the
variable type and the variable name, the name is pronounced as "variable
type pointer." Thus the above phrase came out - storing the address of our
string in this string pointer.
Question: When we say:
cout << school_ptr << endl;
What would be the thing that'll be shown to the user? The answer is the
address of the "school" variable. Not just the address of that variable, but
the address of the letter "U" - remember that string is an array of
characters. Then how many memory locations would this school variable use?
The answer is determined by so-called "memory arithmetic" where moving from
one item to next is determined by how many bytes does a given variable use.
In our case, since the string holds twelve characters, it would use twelve
bytes. I'll come back to how this works later when we investigate memory
arithmetic and how many bytes each variable types occupy.
Now we know the address of something, but how do we find out what exactly is
stored in there? This is done through "dereference" operator (*). don't be
confused here: When one declares a pointer, the asterisk is used; here, the
same operator is used to dereference, or find out what's stored in that
particular memory address. So, if we change the above print statement to:
cout << *school_ptr << endl;
It would print, "UC Riverside" on the screen. What a huge difference... (you
may think it is not a huge difference now, but as we go into all sorts of
adventures with dynamic memory, this becomes important).
at least I hope this gives you a brief introduction to pointers - yes,
that's why i asked that question on the subject line. As we go along, you'll
get a chance to talk to "memory manager", find out how he stores static
versus dynamic memory and all sorts of nasty things that he can help you
prevent, such as segmentation (or seg) fault (which requires extensive
//JL (UCR)

Wednesday, September 1, 2010

C++ and other topics: what now...

At this point, I'm taking a short break from writing things about C++. But I
hope to start writing about other useful goodies by tomorrow - with a new
topic at hand. Some of the upcoming shows include a detailed word on
pointers, how to derive specialized objects from a base class, notes on
other OOP topics (polymorphism, function overriding, etc.) and memory
management (the big three). The last topic for C++ show would be a summary
of my experiences as a student programmer transitioning to the "real core"
of computer science - data and how we can work with it, and a general
overview of data structures - the show coming after C++.

What a surprising news: downfall of WP7 and rise of Android for screen readers...

Code Factory, the developer of Mobile Speak series of screen readers and its
accompanying accessories, just announced that they are working on a screen
reader for Android. In addition, CF just aannounced that, due to some
programmability changes, the initial version of Windows Phone 7 will not be
supported. I guess it's time for me to learn more about Android and how it

Tuesday, August 17, 2010

C++: Misc notes 5

I'm sure learning about classes is a new thing for most of you, so I decided
to have you create a table class - since I think it's one of the simplest
object that i can think of. i shouldn't have put in double variables for
width and length, but I put that in their because we need those for later
when we get into inheritence.

Few more misc notes:
* When designing a class, write out what the properties of a class should
have, as well as means of manipulating and getting info from it.
* Be sure to include scope resolution operator, otherwise the ocmpiler will
complain about undefined variables and functions.
* When writing interface files, include semicolon at the end of the function
signature; in the implementation, you don't include a semicolon when writing
the body of the function in question.

That's all I can think of at the moment...
// JL

C++: Exercise: creating a small class

By now you should have understood the basics of creating a class in C++.
Let's put this info into practice:

This exercise is in two parts. The first part is creating an interface file
(.h) for a class, and the second one is creating the implementation (.cpp)
file for this class.

Spend some time coming up with design and implementation of a table class.
The class would describe a typical dining table. The member variables and
functions are:
Member variables:
* Three double variables, representing length, width and height of this
* A string with the manufacturer and a string for uses of this table e.g.
dining. writing desk, etc.
* An integer to store manufacturing date, as well as an integer to store the
sitting capacity of this table.

Member functions:
* A default constructor: Set the width, height and length to zero, use null
string for manufacturer and purpose of this table and set the capacity and
manufacturing date to zero.
* Parameterized constructor 1: passes a string (uses of the table0 and an
int (sitting capacity0 to the object. The length and width must be set to
three times the capacity (in feet), height to 1 (1 meter) and manufacturer
to null string.
* Parameterized constructor 2: Same as first constructor but adds a string
for manufacturer.
* Accessors: Three of them - get_sitting_capacity to return an int,
get_manufacturer to return a string and get_table_uses to return uses of
this table.
* Mutators: three of them - set_manufacturer to set the manufacturer,
set_table-uses to set the uses of this table and set_sitting_capacity to set
how many people can sit on the table.
* Be sure to split the interface and implementation into separate files. In
the header file, include the inclusion guards; in the implementation file,
be sure to add scope resolution operator and include the .h file.

We'll improve the quality of this table class much later when we create more
types of tables on top of a base table (be prepared for inheritence...).
// JL

C++: Few misc notes on classes...

It's been a long time since I've posted about CPP - been busy with school
and learning new things. So, I'll take this time to go over few
miscellaneous notes on creating classes.

First, when you create the interface file (classname.h), you need to include
so-called "inclusion guards." These are actually commands to C++
Pre-Processor to not include the file again once the file has been created.
A typical inclusion guard goes like this:
#ifndef __classname_h__
#define __classname_h__
// The content of the header...

Friday, August 13, 2010

The future of blindness notetakers and other opinions...

Just wanted to write my feelings on a discussion that I had on a notetaker
Yesterday, some people on the GW Micro list for Braille Sense products
started talking about the future of blindness notetakers in general. (here,
a notetaker is a device used to take notes and do other tasks; in this
context, a specialized computer with Braille input/output). The core topic
was whether current blindness notetakers (herein refered to as blindness
PDA's) have any future viability, and various discussions on connection
between current mobile computing trends and blindness PDA's on the market
today. While some said that notetakers will not go away mostly because of
use of Braille I/O, others pointed out recent developments in ever changing
technical demands and needs as reasons for demise of notetakers as we know
As a participant in this discussion, I cited with both sides: that Braille
system is the most effective way of communication between us (blind) and
sighted peers, but mainstream development must be taken to account when it
comes to discussing future of these devices. I went so far as declare that,
if there is no openness in platform, there will be no progress in
development (currently, the top PDA's, BrailleNote and Braille Sense does
not have an SDK). After several hours of debate, a GW Micro representative
finally stepped in, clarifying (indirectly) about the nature of the list in
question - a support forum for users of Braille Sense family.
So, here I am, composing this blog post in response to all the messages that
were sent to that particular list and observing message trends on other
lists - thus, here goes my opinions:
First, let's discuss the communication channel between users and a
manufacturer. The background is that there is a opinion that "... there is
no communication, or little messages from HumanWare ....". That, I'd say, is
not true for a number of reasons. First, Humanware does respond (mostly in
private), it's just that the messages coming from Canada has slowed down
somewhat. These days, that trend has somewhat reversed (not entirely), with
some tech support reps responding occasionally to messages on the
BrailleNote list. Second, it should be noted that almost all answers on that
particular list comes from "expert users" (including myself) who knows ins
and outs of KeySoft architecture, leading to a possible impression that the
company does not respond much. You may notice that all "hacks" and tech
information was sent by several individuals, including myself, Alex Hall,
Nicole T., Robert Cummings and other experts, with hacks and info ranging
from bug reports to most advanced info so far - changing system sounds and
finding memory leaks under keysoft.exe (which plagued models prior to Apex).
Thus, just because the company does not respond publically does not mean
that the company is not responding at all - it's just that the reps do
respond, but in this case, it's the very nature of the list that drives BN
users forward.
Second, let's ponder the thought of notetakers and programmability.
Computers are meant to be programmed in some way - which I think is the
greatest invention since 1945. Notetakers, in essence, are computers
themselves - a specialized computer, in fact. If the logic statement that
"computers are programmable" holds true, then it'd make sense that
notetakers are programmable as well. The one huge drawback is the
availability of actual tools of doing it (called SDK, or Software
Development Kit). In connection with our PDA situation, Braille Sense (more
properly called Braille Hansone (pronounced han-so-nae) in Korean) has
Contents sDK in Korean as of 2010; HumanWare does have application framework
to support writing new programs under the hood.
This leads to several questions: Will HIMS (Human Information Management
Service), the producing of Braille Sense, come up with English version of
their Contents SDK? Will GW Micro, the North American distributor of Braille
sense, work with HIMS to develop English extensions to popular contents
(which includes a handy Bible reference program for Koreans)? Will Humanware
Group, maker of BrailleNote family, release a public SDK for KeySoft? In my
view, I'd say it'll be great if there would be SDK's for both platforms so
that those who are familiar with programming can write useful software for
these devices (by the way, both were developed in C++). But that involves
time and effort, and testing is required to make sure that the documentation
for the SDK is up to date and as accurate as possible. Then you may ask,
"why don't we write a simple program using C++ for these devices?" The chief
problem is the communication method that is in use - Braille characters,
which requires special attention when it comes to input/output routines, as
well as design considerations for general embedded devices - slow
processors, low memory, specialization, etc. I'll continue to advocate for
SDK's for these platforms until it is here - for the future of these
Speaking of future of these devices, this brings me to the final opinion of
the day: connection between blindness PDA's and mainstream trends. As we
have examined, if notetakers are computers, then all things related to
current happenings with mainstream embedded systems must hold true -
changing perception, more accessible mobile technology, etc. The perception
these days, in my observation, is miniaturization and more attention on
accessibility in general, as well as being independent of cables via
Bluetooth and Wi-Fi. Also, people want more creativity and openness in terms
of development, as well as being able to keep in touch with others at all
times (almost all times, which I believe is the success behind Android
environment running on top of modified Linux kernel). With this trend in
mind, I'd say the trend for blind people would be more independent devices
using wireless means of communication i.e. having almost the same devices as
sighted peers with an added way of communicating with them via Braille
support. In my view, notetakers will be around for a while, but current
trends and changed perception on mobile tech world will cause blind and
visually impaired computer users to reconsider their options.
In closing, I'd like to leave you with a well-known phrase: a frog in a
pond. In other words, it is time for enlightenment in blindness technology
world to inform citizens that there are other choices out there, and the
full power of a computer will not be realized until useful programs come out
for the above platforms. I look forward to a day when users will be the
chief driving force behind innovation and creativity, with many creative
apps produced for the benefit of the future generation to come.
Signed: Joseph Sungwon Lee
University of California, Riverside (class of 2012)

Saturday, August 7, 2010

C++: The car class part 3: Accessors and mutators

Last time, we learned how to construct our car class. This time, let's find
out how to obtain properties about a given object and setting its properties
based on our input.
Note: Some of the function names may differ from those that I've declared

Let's return to the declaration of a car - a 2008 Ford Mustang, but let's
say if we don't know what the released date of that car is. How do we find
out various properties i.e. values in a member variable for our car? This is
done through accessors. As the name implies, an accessor "accesses" the
private data of our object (encapsulated member variables) and returns
whatever information we need.
A typical accessor looks like a regular function with a return type, a
function name (with or without arguments, mostly without) and a return
value. So, for instance, if we want an accessor to tell us what the model of
our car we are dealing with is, we can say in English:
Can you return to me a string for the model of our car?
In C++, this is translated as:
string Car::get_model()
return model;
As we've seen before, since we are dealing with a member function of our own
class, we need to provide a scope resolution operator. But here, we need to
type that in right after typing the return type, then the object name
followed by the operator (::). In our context, the only thing that this
function (accessor) would do is tell me the model of our car, as seen below:
Suppose if I want to get the model of a car object called "my_car" and store
it in a string variable called car_model. I can do it using the following
In English: Create a string variable called "car_model" and assign to it the
string returned by the get_model function of our car object called "my_car".
In C++ (in main):
string car_model = my_car.get_model();
Noticed something familiar? As you might have guessed, my_car is our car
object, and the "dot" operator tells us that get_model is a member function
of our car class. So, in this situation, the string variable (car_model)
would be initialized into whatever is returned by this accessor function (in
our example, a "Mustang).

Another example: Suppose I want to find out when a particular car model
(Ford Mustang) was released. To help me out here, I need to create another
accessor function to tell me of this fact, which would be appropriately
called get_release_year that would return an int of model year. Can you tell
me how you would write this accessor? To help you solve this problem, I will
not write the accessor here - it's up to you to design the accessor based on
the following: the year variable in the car object is called release_date,
and the accessor does not take any arguments. After you're done, you need to
create an int object to store whatever is returned by this accessor

Now we know what the release date and the model of our car is, how do we set
our own input as a car property e.g. a different release year, different
manufacturer, etc.? This is done through mutators - to assign something from
one thing to another. Unlike accessors, we don't need to return anything
e.g. a return type of "void" would be used because all we are doing is just
assigning our own data as part of an object.

For instance, if I want to tell the computer to change the release year of a
car, I can ask the program to get my input and assign it to the release_date
property of our car class. In English, this could be done as follows:
* Create an int called year that will store the new release year of our car.
* Have the user enter the new release year, then pass it to our mutator to
be set as the new release date of our car.
A bit complicated, but I'm sure this can be done. All we need is the
following four lines of C++ code (again, scope resolution operator comes
void Car::set_release_date(int & d)
release_date = d;
The code above did what it was supposed to do - get our input and assign it
to the release_date member variable of our car. But how do we make it
"interactive" e.g. get the actual input? Let's use my_car object once again
on the following C++ code:
int year; // The new release date of our car.
cout << "What is the release date of this car?" << endl;
cin >> year;
As you can see, we are taking the value stored on "year" and assigning it to
the member variable.

Another example: Suppose if I want to change the manufacturer and model of
our car. Try to come up with your own mutator for these ones using the
following hints: the target variables are named "model" and "manufacturer",
respectively. We want to make sure that there would be two mutators - one
for each of our member variables. Create a mutator function to take a string
argument and set it to these two member variables. Then create a block of
main() that will ask the user to type a string for model and manufacturer
and set it to the member variables of our my_car object. Again, I'll not
give you my code - just want to find out if you've understood it. Don't
forget: in the mutator functions, you need the scope resolution operator...

I think that provides a general overview on accessors and mutators. I'll
come back and write few things about these two in a sec...
// JL

C++: The car class part 2: Constructors

With the basic syntax notes out of the way, let's talk about actually
building a class called "car."
Note: Some of the variable names may differ from what I've declared as part
of the class interface earlier.

Logically, in order for an object to exist, we need to create, or construct
it from scratch. This is what a constructor is. Here, a constructor is a
special function that instanciates, or make an object exist on a computer's
memory. It usually takes a value from input and assigns it to the member
variables of a class; in some cases, we (the class designers) need to assign
default values for our member variables for our classes (called default

A typical constructor looks like:
class::class(type whatever, additional data)
member_var = value;
// Additional ones...

There are quite a few things here. I think this is the first time you are
not seeing a return type for a function like this. Actually, a return type
does exist, but it is not that apparent: that return type is to tell the
program we want to create an object, that's all. Also, I believe this is the
first time you are seeing double colons (::). This is called "scope
resolution operator" and is used for telling us (the programmers) where a
data or a function belongs to. For instance, if we put:
std::cout << "Hi..." << endl;
we are saying that we want to use the "cout" operator under standard
library. Similarly, if we put our class name and the double colon in front
of a print function, like:
We are saying that we want to use the print function - a print function that
is member of an object. This becomes important later when we talk about

Now, let's create a default constructor for our car class - a constructor
that will be invoked when we don't supply our data when we declare a car
object. In order for this to work, we need to provide our own default values
for our car object. For instance, we can say that the default car is 2004
Ford Escape (a likely car). In order to do that, we can say:
* Create a default constructor called "car" with member variables of the car
object (model, manufacturer, date of release) provided by myself.
In C++, it would look something like:
model = "Escape";
release_date = 2004;
manufacturer = "Ford";

So, for instance, if we declare something like:
Car test;
It would invoke the default constructor (the values we've just declared
above). As I've been saying: you need to provide initial values for ALL
member variables of a class.

But what if we want users to actually give us the model, manufacturer and
release date of a car? We can come up with so-called "parameterized
constructor" to take a user's input and assign it to the member variables.
In this context, it would be two strings for model and manufacturer, and an
int for released date (year), with each of them called m, n and r,
respectively. So what should this constructor do?
* Almost same function body and declaration as the default constructor
above, except that we need to provide a set of arguments.
* Here, the arguments would be user-specified properties of an object.
In C++, it would look somewhat similar to what we have up there, except:
Car::Car(int r, string n, string m)
model = m;
manufacturer = n;
release_date = r;
Sound familiar? This is exactly the same thing as the default constructor -
instanciates a car object with values obtained from the users, like:
Car my_car(2008, "Ford", "Mustang");

As we've seen, there are different ways of instanciating a class via
constructors. There are other variations of this concept, namely ones with
different parameter sets, one or more parameters missing (in that case, we
need to "fill in the blank" i.e. provide our own default values for missing
parameters) or copying one object to another (called copy constructor). The
last one will not be seen until much later.

As for declaring an object, in my case, I prefer to use parameters when
instanciating my own object of my own creation. It's really up to you to
invoke either the default or a parameterized constructor when declaring
something of your type. The next topic will be on how to obtain a member
value of an object, as well as setting something to our liking (accessors
and mutators), respectively.
// JL

Friday, August 6, 2010

First impressions of Windows 7

Thought I should write a mini report on what I've been doing lately.
Besides, hope you are enjoying the C++ notes - I'll post more about classes
and introduce you to pointers next week.
As of now, I'm composing this message on my laptop running Windows 7
Professional 32-bit. So far, it's been great - runs faster than Vista and
all my current devices - sound card, graphics and external hardware - are
compatible with this newer OS. As you may know, I'm using a screen reader on
top of the OS to work with programming and other things.
You may wonder how I got this new OS. The answer: I've installed it myself.
Surprised? I know - it is indeed possible for people who are blind or
visually impaired to install newer Windows versions on their own using a
built-in screen reader under Windows. When the installation happens, a
complete image of Windows 7 will be run during install, so I can interact
with setup environment via speech.
I could have chosen 64-bit OS for better stability and fun with more memory;
however, because of compatibility with existing programs and devices, I
chose 32-bit instead. However, I'll make clear that Win7 will be my last (or
second to last) 32-bit OS.
At least that's for now.
// JL

Thursday, August 5, 2010

C++: Creating a car object part 1: class interface

Well, I know you are a bit puzzled by new words and topics for the rest of
this notes series and wondering what should I do next. Well, I was like you
when I took my C++ course. Now being a amature pforgammer for about a year
or so, I'm starting to understand the "under the hood" works done by
compilers when we create custom data types - classes. So, starting from this
post, let's build a simple class - a "car" class - perhaps to use it in a
car manufacturing plant simulator or similar.

The first thing we need to think about is what member variables and
functions (methods) would this car class have. First, let's think about what
properties does a typical vehicle have: the car model, manufacturer, date of
manufacture and its type, among other things. Next, what sort of thing do we
want to do with this car? We need to find out its model and manufacturing
date, as well as have a plant worker label the car's type.

Based on that, a design of a car class comes out to be:
A class called "car":
* Member variables: a string to hold car's model, an int to hold its
manufacturing date, and a string to hold the type of car.
* Member functions: Useful constructors (to make the object exist),
accessors (getters) to find out the properties of a car and mutators to set
a car's property based on user input.
The above code is the English version of a typical C++ code for defining a
car class, which is reproduced below with comments:
class Car
string model; // The model of our car.
int date_of_release; // The manufacturing date.
string car_type; // The type of our car.
Car(); // The default constructor.
Car(string m, int y, string t); // A parameterized constructor (m = model, y
= year, t = type).
// Accessors:
int get_release_date() const;
string get_model() const;
// Mutators:
void set_model(string & m);
There are several things we might have seen elsewhere, but wasn't explained
in detail in code form until now. also, we have quite a new friends out
here, so I'll describe to you what they are:
* Whenever we don't want to change anything stored in a variable, we put the
keyword "const" (constant).
* Notice that I used access keywords (private and public). The private parts
are the member variables - this is called "data encapsulation" where the
outside code does not know what the internal properties does an object have
apart from the object itself.
* The default constructor does not have any arguments; however, we need to
initialize ALL members of this class to a known (or other) values as
default, which I'll show you on the next post.

The above class code is sometimes called "class interface" or class
definition, and is usually stored in a header file with the class name e.g.
car.h. The actual "body" of our class, or class implementation is stored as
a source code file e.g. car.cpp. Although it is possible to write the class
interface and implementation under one roof, it is far more easier (in terms
of maintenance) to store them separately (this is called multi-file
compilation). But when we use this method, we need to put in more extra text
to really make sure that the compiler would know what to do when
encountering a class that was defined already (called inclusion guard). The
full text of a typical .h file will be shown on the next post with few more
definitions. After this, I'll go through creating a class implementation
with comments about constructor creation.
// JL

Wednesday, August 4, 2010

Opinion: Possibility of JAWS for Windows Mobile

In 2003, Freedom Scientific announced a brand new entry into mobile
notetaker aurena: PAC Mate, a customized PDA hardware with Braille keys
running under Pocket PC 2002 with popular screen reader - JAWS for Windows -
written for Pocket PC operating system. This was a breakthrough, marking the
debut of Windows Mobile family of operating system for people who are blind
or visually impaired. Previously, the only PDA running on top of windows CE
(which powers Windows Mobile) used custom interface for interacting with a
user, thus usage of mainstream software was a big hit with Freedom

The biggest advantage of PAC Mate (PAC = Personal All-purpose Computer) was
the ability to run third-party programs written for Pocket PC environment.
This meant work was being done a FS to prepare for launch of PM, including
scripting Pocket Word and other built-in programs, as well as testing
hardware and software products to be compatible with PAC Mate's initial
release. Since then, other generations of PAC Mate (after initial BNS/TNS
running under PPC 2002) followed, including PAC Mate BX/QX (launch in 2003
under windows Mobile 2003) and PAC Mate Omni, launched in 2007 using Windows
Mobile 6.0 Classic.

Although using third-party software and hardware was a big plus for PAC Mate
series, there is one huge drawback, in my opinion: too much customization of
JAWS for Pocket PC executable for built-in drivers and hardware
configuration only, which defeats the purpose of mobile computing under
today's standard - changing devices on the move to suit a person's needs.
Although dedicated hardware modules does have its benefits, under today's
rapidly changing specifications of mobile devices, it would be hard for
Freedom Scientific (in my opinion) to market JAWS for Pocket PC on a
platform that is around three years old, even though FS markets it as
running the "latest hardware specs." To understand what I mean, here's the
hardware specs for a typical PAC Mate:
* CPU: Intel X-Scale PXA255 at 400 MHz versus other ARM CPU's running at
around 600 MHz.
* RAM: 64 MB compared to 256 MB found on today's phones.
* Flash ROM: 128 MB compared to 512 MB to 8 GB found on some PDA's and
Using these specs, it'll be hard to believe that FS's strategies would work
when it comes to marketing a customized hardware. Thu my opinion of
releasing JAWS for Windows Mobile as a software product rather than as a
hardware-bound executable.

There are numerous benefits to this move. First, a user can change his or
her device depending on personal needs. Second, it'll be somewhat easier for
Freedom Scientific to port JAWS for Pocket PC to mainstream hardware
platforms, given that it utilizes generic drivers for basic hardware
configurations and making sure that scripting works as expected. Third,
it'll be useful for FS's marketing strategy to point out that JAWS would be
a universal screen reader for some of the popular platforms out there -
chiefly under HTC devices. Fourth, if generic Bluetooth stack is
implemented, it'll be easier for third-party Bluetooth Braille displays to
interface with JAWS for Windows Mobile among other devices. Despite these
suggestions, there's bound to be compatibility issues, but when thinking
about this move, I strongly support that releasing JAWS for Windows Mobile
as a software product would be more beneficial and cost effective, as
evidenced by above reasoning.

At least that's what I have. If you have any comments, please let me know...
// JL

Tuesday, August 3, 2010

C++: Meet some terms used in classes

Well, I hope you understood the last message on classes - what they are and
things we can use to create rich set of custom data types. Now, let's take a
look at some terms used when talking about classes and objects.

First, the word "class" itself. In tech language, it means, " programmer
defined data type, a container containing data and functions for a specific
object." So, for instance, a computer can be a class, since a programmer
needs to create that custom data type for working with computers e.g. CPU,
RAM amount, etc. Or, a class might be everyday objects, including tables,
chairs, doors, rooms and so forth. Or it could be something specific to a
particular task, such as computer time, dates, appointments and even word
processor documents.

In order for us to work with classes, we need two things: member variables
(the properties of a given object) and functions to access and set member
variables (called member functions). Member variables could be anything,
including numbers, decimal numbers, strings or even a class that a
programmer has created. Member functions include ones to create, or
instanciate a class to existence(constructors), mutators to set member
variables and accessors to get a member variable. The mutators and accessors
are sometimes called "setters" and "getters", respectively.

In terms of syntax, a class has usual appearance of a function except that
there are no parentheses for storing arguments, and that you need to put a
semicolon after right brace(};). For instance, if I want to create a class
called "car," I have to write it as:
class car
// Whatever we need to put in...
The whole discussion of why we put in semicolon would be discussed much
later when we go into data structures.

Few more short definitions:
* Constructor: A constructor is a special member function to instanciate, or
make an object exist. There are usually two types of constructors with
variations of each of them: a "default constructor" for storing default data
for that class, and "parameterized constructor" to put necessary arguments
that a user (programmer) types when creating a variable of that class type
(after all, classes are custom data types).
* Mutator: A mutator sets something to a member variable of that class.
Usually they are "procedures" (void functions) with a prefix "set".
* Accessor: An accessor is a function to retrieve values stored in a member
variable. They have a return type and usually they are prefixed by the word
* Access keyword: An access keyword defines how much information, or data is
exposed to other programs. There are three of them: private, useful when a
programmer wants to limit access to a member variable or a function to a
given object only, public where any program and data (anyone) can access the
object and protected, which means that a child class (an inherited class
from a base class) wishes to use existing privilages of members of a parent.
The third keyword requires special attention - thus, I'll come back to it
when we build another layer of custom classes on top of a base class (called
* Destructor: A destructor is used to destroy an instance of an object. This
requires a keystroke in front of a constructor, which I'll show you much
later when the time arises.

And other terms, which you'll meet as time goes by. Starting from a few
posts later, I'll demonstrate an example of creating a simple class (called
car). Along that way, I'll give you some tips on creating your own classes
and have you go with building your own simple objects, declaring it under
main() and actually using it.
// JL P.S. Gotta run for CS lecture...

Monday, August 2, 2010

C++: Introduction to classes

Until now, we have used built-in data types or data types that C++ comes
with. Starting from this post, I'll dive into ways in which we can have our
own data types for solving various problems. Along the way, we'll
investigate how to manipulate classes, pointers and other more advanced

First of all, as this is just an introductory post, let's ask ourselves,
"what kind of data can a computer store?" Obviously it needs to work with
numbers, so an integer data type is provided. Next, we want to have a
computer work with decimals, so we use floating point (decimal) numbers, in
our case, a double number (technically called double precision floating
point numbers). However, sometimes, we want computers to store our names, so
we use characters and strings to help us out with that task. Finally
(almost), we want computers to make decisions based on user input, so we use
Boolean (tru/false) values. There is one more built-in data type called
pointer - an address of where data is stored, but we will not meet its true
form until later.

But how about if the problem we wish to tackle cannot be solved using the
above data types above? How about if we need to work with various game
scenes, a list of rooms or counting number of cars at a parking lot? What if
we want to create our own programmer-defined data types, or custom data type
that we can use for solving other kinds of issues? The answer is a perfect
"yes, it is possible to create our own data types". C++ and other
programming languages allows us to create and work with our own data types,
known as classes and objects. Any data that a computer can work with -
numbers, names, and even files - are called objects - hence, the phrase
object-oriented programming (OOP) came out, which means we can manipulate
these "objects" to help us solve problems.

So what other kinds of data we can "create"? There are millions of them,
including a desk object, a chair, a video game character or even the stars
on the solar system. Each of these data types are not defined in C++, so we
(the engineers) need to create them, or define them. For example, a "video
game character" object would have properties such as its name, various
actions it can perform and sounds it can make, if any. Similarly, a desk
would have descriptive values such as its length and width, its uses (dining
table, study desk, etc.) and who made the actual desk (the manufacturer).
All these are stored as an object, or class as private member variables
within it (we'll come back to the meaning of that statement when we visit a
"lab" i.e. exercises and examples for creating a class). Also, the various
actions that can be performed on it can be dealt with via creating member
functions (we've seen this phrase before, but we'll examine the very meaning
of that phrase shortly when we create an example class).

Now, can you think of any other objects we can create using this method? If
you have any, please leave a comment... We'll examine how it can be done, as
well as some terminology used when talking about classes starting from a few
posts later...
// JL P.S. Need to study for a homework at UCR.

UCR: UC Riverside, Unstoppable Christ's Revival

Just found this grup on Facebook:

Sunday, August 1, 2010

Who is God?

Hi, I thought, since it's Sunday and I am a Christian, I thought I should
ask this question at large to see people's reactions.

So what or who exactly is God? Many people say that God is just a creator, a
supreme being with supernatural powers or use descriptive language to
describe God. There are debates about this, including a notion of god's
gender, whether there is only one god or other gods, or is there such as
thing as a deity.

In my view and after my experiences, there is a God out there "somewhere."
I'd say many people believe there is no god because they canot see one. I'd
also say that people believe in many gods due to various natures surrounding
earth's events. In my case, there is one and only one god - the Jewish
thought calls him "YHWH", commonly translated into English as LORD God. This
God is one and only one who knows when the earth was created, who knows
exactly how many genes does a human have and even know when the world as we
know it would come to an end. This god, we (those who know it) call Father.

So who is this "father?" After talking with him for several years and
studying his word (bible), I came to the conclusion that the best words to
describe him are "love" and "caring." He is full of love - even loved us
(humans) to send his one and only son, so that he can die in place of us
because of our sin (John 3:16). He is also merciful - loving us a lot that
he puts us through "tests" to help us trust him more..
He is also caring for his people. Even though we do not see him, we (the
people who know him) knows his presence, because we have walked with him for
so many days and years. Besides, he gave us a human representation of him
and his word - jesus Christ of Nazareth (John chapter 1).
But how do we know God's presence even though he is a spirit? We know him
through faith and his words that teaches us who he is. Also, God is known
through people's actions and what we say - after all, the proof of one's
faith is his or her actions.
So who exactly is God? To me, he is many things, including "my creator,"
"king of kings," "the ultimate beginning and end," "my friend," "my helper,"
"my professor" and so many other words that I cannot think of. That's how I
view and know him.
Just my thoughts, that's all.
// JL

Saturday, July 31, 2010

I'm so proud of my school: Miss Korea 2010 attends UCR!

I didn't know this bit until now: Miss Korea 2010 (Jung So-ra) attends UCR
(most likely poli sci major, as she wants to become a diplomat). I'm not
sure if I know here or not - I wish her good luck at being a highlander (I
hope to meet her some day)...
Here's the link:

// JL

Thursday, July 29, 2010

C++: Intermission 4

I didn't learn what a member function is in proper terms until experimenting
with designing a custom object. Before then, I just memorized what a given
function does, not knowing that I needed to learn the true workings of these
functions for later use.
As for vectors, at first I just memorized the function names and what it
does. As my experience with vectors grew, I began to appreciate what each
function does exactly under the hood - especially after writing an integer
vector class as part of a lab assignment.
You'll see what I mean by the words "class" and "object" starting from the
next post, as creating our own custom data types requires significant
investigation and hours of notetaking. The very concept of working with our
own data types would be covered in detail for the remainder of our
discussion of C++, with occasional notes on other useful things you need to
know such as memory operations, file operations and so forth.

Again, if you have any comments about these notes, please let me know...
// JL (UCR)

C++: Misc notes 4

Few misc notes about member functions:
* You need to first include the desired library before you can even declare
that variable type and use its functions.
* There is a handy function to combine two or more strings, ironically it is
the plus (+) sign. For instance, if I want to have three string variables
named A, b, and C, assign some text string on A and B and combine these
strings into C, I would write:
string A, B, C; // Which is legal.
A = "Hello, "; B = "World!";
C = A + B;
cout << C << endl;
If we run this code, it'll print out "Hello, World!" to the screen.

I think that's it for now... If you have any comments, please let me know.
// JL

C++: Words on previous posts and a set of experiments...

By now you would be wondering why I discussed member functions for strings
and vectors. You see, they are not built-in data types that comes with C++ -
int, char, float, bool and pointers. The strings and vectors are what we
(the programmers and engineering students) call custom or programmer-defined
data types, more commonly known as "classes". A string is essentially an
array of characters; a vector is a specially enhanced version of a typical
array because there are more than one data that it holds - the data item
themselves and a special assistant that keeps track of data. Since they are
not built-in data types, we need special ways of dealing with it, popularly
known as member functions. We'll examine if it is even possible for us
(programmers) to create custom data types and what components are required,
if any in future posts.

So, I guess that sums up our discussion on member functions. Now it's time
for some hands-on experiments - get your editor and compiler ready...

1. Create a string variable named month and store the current month
according to system date. Then create another string variable named "s"
which will store the first three characters from the month string. Then
output both variables to the console. Provide:
A. An English version of how you would accomplish it.
B. Try translating your English words into C++ (hint: see a detailed post on
strings; you need a small assistant...). Compile your code and see what

2. Your friend asks you if you can write a small financial recorder program
to store how much money he has spent for a given month. You ask him how it
should do it, and your friend tells you to keep asking for monthly
expendatures until he types -1, at which it should output all data to the
A. What would be the most useful data type and monetary variable to use if
you want to work with whole numbers?
B. Since we are dealing with unknown number of months, what would be the
variable declaration and a useful function to add more items on this data
type you chose? (hint: look at the first example of the declaration on one
of the previous posts...).
C. Provide an English version of how you would accomplish the task outlined
D. Translate your comments into C++, compile it and see what happens.

3. Suppose if we want to create a vector of ten names for a class roll call
A. What would be the data type for this vector?
B. How would you declare a vector of your chosen data type to hold ten
C. What would be more useful to add names to our vector with "fixed" element
size at the beginning: a push_back or a for loop to ask for name and store
it in the elements? (hint: one of them requires another string variable to
be placed at the beginning of our program).
D. Provide an English version of your code, then translate this into C++,
compile it and see what happens.

4. Using our roll call sheet above:
A. Suppose now you want to add more names to it. The program would ask for
names until you type "done" at the prompt, at which point it should print
out current names in the entire vector. What would you do (both in English
and in actual C++ code) to accomplish this task?
B. Suppose you find that you typed the last two names wrong. You want to
delete these two names and type the new names. What would you do (both in
English and in C++ code) to solve this problem?
In both cases, after writing C++ code, compile it and run it.

My opinions and a working program will be shown at the end.
// JL

C++: A detailed tour of vector operations

Last time, we looked at how to manipulate strings and learn what a member
function is and how it is used. In this post, let's revisit the concept of a
member function using vectors.

Just like strings, in order to use member functions for vectors, we need to
include vector library:
#include <vector>
Just like strings, we can manipulate vectors, such as find out how many
items are in a given vector, access elements, add or remove something and so
forth. Let's examine it in more detail.

To declare a vector, you would use the syntax like:
vector<type> var;
Where "type" is the data that the vector would hold, and "var" is the name
of this vector. For instance, we can declare a string vector like:
vector<string> s;
Note the arrows (less-than and greater-than signs) surrounding our data
type. As a matter of fact, there are two other popular variants of our above
code - one is used to tell the computer how many items will be stored on
that vector, and another one goes further and assigns each element to a
unique value. For instance, if we want to store five integers in a vector
called "item", we could use:
vector<int> item (5);
Furthermore, if we want to assign the value "10" to each of the elements, we
could say:
vector<int> item (5, 10);
In our second declaration, what happens if we output our vector using for
for (int i = 0; I < 5; i++)
cout << Item[i] << " ";
On the screen, the result would be five "10's" being displayed on the
monitor, just like our output routine from our example earlier on another

But we don't really want to use a fixed number for this kind of output code.
What if the number of items change? Thankfully, there is a dedicated
assistant that helps us here: the "size" member function, which gives us how
many elements does a vector have (you may have seen it before): v.size();
So, if we use this function, we'll get the output code similar to something
you may have seen before:
for (int I = 0; I < item.size(); i++)
cout << item[i] << " ";
And, as I've said before, we use subscript operator ([]) to access elements.

As for adding and removing things, in addition to the push_back function
we've seen, there is a dedicated function to take out the last element of a
vector: the pop_back member function. The job of this function is to delete
the last element in a vector and decrease the size of our vector by one. We
call this function similar to how we call size:
Don't worry about arguments here - it does not need it. So, for instance, if
I invoke the pop_back on my item vector, it would delete the fifth "10" and
decrease the size by 1 (so the total would be four numbers):
Now, if we invoke the for loop to print our vector, it should print four
"10's" instead of five. I guess that's enough on vectors for now - enough
basic functions and tips to get you started on a small program to work with

By now you may be wondering why I am giving you tips on so-called member
functions. This was done so that I can gradually introduce you to the
concept of objects and classes, or custom (or programmer defined) data
types. I'll provide more details on my decision and flow of our discussion
on the next post. Then you can have a hands-on experiments with working with
member functions.

// JL

Tuesday, July 27, 2010

C++: Examining string of characters

By now, you would know how functions work in basic terms - how to declare
it, arguments and concept of return values. In this part, we'll examine more
details about functions by looking at what we can do with string variables.

There are a number of reasons why I chose strings for this series. First, as
you might have guessed, a string is essentially an array of characters.
Second, there are a host of functions we can use to manipulate strings,
including finding an exact character within a string, taking a part of a
string and assigning it into a new variable and so forth. Third, using these
functions, I can gradually introduce you to the concept of classes, objects
and member functions, as you'll see after this chapter.

So, as you have seen, we declare a string just like any variable:
string var; // Where var is the name of our string variable.
However, as you've seen, in order for us to work with strings, we need to:
#include <string>
Since "string" is not a built-in data type (although it is an array of chars
though). The string library, in addition to allowing us to declare string
variables, hosts a number of "helpers," or member functions. Let us meet our
helpers, shall we?

Sometimes, you may need to take part of a string and assign it to something
else - perhaps for comparing two strings or printing just a portion of that
string. To do this, we use a "substring" function (substr) to take part of a
string and use it for other purposes. The syntax is:
string_var.substr(start_of_selection, length_of_string);
Where "string-var" is our string variable, "start_of_selection" is where we
want to start the substring routine e.g. where a portion of our string
begins, and "length' is the number of characters that the substring should
"capture" e.g. set aside for further action. Note that the first character
in a string starts at zero (0.
For example, say if I have a string variable with the following string:
string text = "Welcome to Blogger.";
The total length of our string is nineteen characters, so the length range
would be from zero to eighteen. Suppose if we want to set the word "welcome"
aside for another string variable named "intro." We can do the following (in
We want to take a portion of our string, so we need substr function. The
start of our portion is at zero (at the letter "W") and will run for seven
characters (welcome). Using what we've just obtained, assign this word to
another string variable.
In C++, it goes something like:
string intro = text.substr(0, 7);
In other words, we've just taken the first seven characters on our first
string (under text variable) and assigned it int "intro" one. In terms of
arguments, the start of substring could be anywhere - at the start of our
text (zero) or even halfway across. As for length, it could be any length,
provided that it does not exceed the total length of our source text (we'll
see how we do this below). For example, if we want to select the word
"Blogger" from our text above, we could say (assigning the substring to blog
string blog = text.substr(11);
Notice that I only put one argument, and that is perfectly legal. What we
have just performed was select from the letter "B" to the end of our string.
So, if we output our blog variable:
cout << blog << endl;
It'll print, "Blogger."

But how do we know the length of our string? The next friend we'll meet is
the length function. This just tells (returns) the length of our string. Let
us return to our message under "text" variable. If we use the code:
size_t length = text.length();
Few things here: don't worry about size_t, it's just an enhanced version of
integer variable used to store size of a string or similar things. The
length function did not take any arguments (and that is legal); what it will
do is just tell us how many characters (technically elements) does our array
of characters (string) has - in our case, 19.

Another quick visit to another friend and I'll let you go, and that is the
question of how we find a specific character in our string. Logically
enough, this friend's name is find function, which it does what it is
supposed to do: find a character for us. All we need to put in this member
function is just one argument: the actual character we are looking for. What
will it give us in return? The location where this item is located, if it
can find it.
For instance, using our text variable, suppose you want to find the first
instance of the letter "g". We would write:
Or something similar. Be sure to put quotes around the character. Luckily
for us, there is a "g" - it's in location 14.
As a side note, we can use this function to find anything - even a word.
What it will return is the location where the start of our search string is
located. (a teaser: this fact becomes very important much later...)

I think that's enough for now. Hope you understood the concept of a member
function and examples of its use in string library. In the next post, we'll
meet more member function friends, this time the ones assisting vectors.

P.S. Hope this was simple for you. I apologize for any errors or
misinformation on this post...
// JL

Monday, July 26, 2010

C++: Intermission 3

Like most of you, I found the concept of arrays and vectors a bit intriguing
at first. But after reading many C++ resources (including and
experiments, I was able to understand and work with vectors as though they
were regular data types.

As for functions, I understood the concept for the most part. The only thing
that I didn't get on the first try was a precaution of too many lines of
code in a given function. I thought I should just write the whole story
within a block of code. However, after listening to lectures from my
instructor and visiting his office hours, coupled with my own findings that
I couldn't really follow my code, I decided to split a long function into
smaller parts - and it worked. A function is supposed to do one thing at a
time; if it tries to do multiple things at once (unless if a function is
optimized for multiple processors), it is best to split this multipart one
into smaller ones.

I think that's all that I have to say regarding functions. Starting from
next installment, we'll go into things such as member functions (we'll
examine string and vectors more), as well as creating our own data types
(classes or objects) to help us explain where member functions came from.
// JL P.S. if you have any comments, please let me know...

I'm back at UCR to attend summer school...

I'm now back at UC riverside to study programming during summer school. As a
result, I hope to publish more programming notes...
// JL

Sunday, July 25, 2010

C++: Misc notes 3

Few additional notes:

You can in fact put a group of functions in a file. This is useful if you
want to work with a group of functions as modules. To include this file, we
need to place this header (.h) file ins the same direcotyr where our source
code (.cpp) is located. Or, we can just add it as part of our project (via
VS). When you include your own header files, be sure to use quotes instead
of arrows. Also, it is perfectly possible to use two separate files - one to
store function signatures for your functions and another for spelling your
function body. We'll examine this one in more detail later.

Also, as a courtesy for others and as an added style, try putting comments
about your function before you write it i.e. above the actual function body.
That way you would know what your function does, what the arguments should
be and what values to return or pass back to the program which calls your

I think that's enough for now. When I arrive at UCR, I'll start by writing
my experiences with functions, as well as the reason why I mention functions
and vectors together.
// JL

C++: Few more function notes and practice exercises

As we wrap our discussion on basics with function, I'd like to point out few
opinions, styoes and miscellaneous ideas about functions. Then, we'll dive
into some practice exercises with functions to put our knowledge into

As for function arguments, you can put anything in there - an integer,
double, char, string, vectors, arrays, and even our own data types. A
function argument, as described earlier, is the data that a function will
use to process something. A function can have anywhere from no argument to
four or five (or more). When we speak of arguments, we say a program passes
an argument to a function. For example, for our kilometer to mile converter,
the argument would be the km value, and when main() cllas our conversion
function, it'll pass an integer value (named km) to our converter so that it
can process it.

As a side note, you don't really have to use same variable nemas as the ones
used in function arguments. For instance, back in the converter function,
we've declared an int argument called "km." However, in the main, you can
write other variables as long as it is an integer e.g. if we pass in, say,
kilo as our argument to our function, the function can work with it since
it's the same data type as the argument itself.

Speaking of passing in an argument, we can use two methods: passing in by
value, or using a reference (an address of a value). The chief difference
(at least how we write it) is that there is an additional character that we
use when passing in a value - an ampersand (&), which is called "address of"
operator. In this context, passing in by value means we want to change the
actual value of the argument, whereas passing by reference means we don't
really have to change the values stored within that address (this becomes
important as we design our own classes).

Another note to consider: It is recommended (from Practical C++ Programming
and from my professor) that a function's body should not exceed no more than
ten to fifteen lines of code. If this happens, it'll be hard to follow what
a function is doing, thus my professor recommends splitting a long function
to two or more smaller (helper) functions. This may seem not an easy thing
to follow (especially for me), but when we need to look up a body of a
function quickly to skim through its process, a very long function body
would be a waste of time and space on an editor window. Besides, splitting a
long function into smaller ones helps us reuse our code, thus saving time
and complexity. I'll return to this concept later when we dive more deeply
into functions.

So, I'm sure you now have a basic grasp of what a function is, how it works,
components and uses. Thus, let's put our theories into practice by writing a
few simple code:

1. suppose if we want to create a function that'll print out a vector. This
version is an enhancement of our vector output routine that we've seen
before. First, describe in English what the components of this function
would consist of - return type, name, possible arguments, return value (if
any) and algorithms to print out a vector. (hint: actually, you don't need
to return anything since we are using a lop to do this). After this, come up
with a possible C++ version of your English description.

2. Create a program to check if you are old enough to drink alcohol. In
this one, try to come up with at least two functions: one to ask your name
and age, and another one (called by the first function) which takes your age
as an argument to decide whether you are old enough (over 21) to consume
alcohol. Then call this first function in the main() function.
Few hints:
A. Since we are doing a procedure, what would be the return type for the
first function?
B. In the second function, how to we test to ensure that the user is over 21
or not, and what variable do we need to assign the return value as a true or
false statement?
This one sounds a bit complicated, so I'll post some portion of the program.

3. Create a function to convert from Celcius to Fahrenheit, call this
function in the main() and assign a double variable, "temperature" to the
result of this function i.e. the value that the function returns. Note that
you may need to use operator precedence (parenthesis) to helop you out
(foruma = -40 + (1.8 times celcius)). When we run this program, the computer
should ask for a temperature in celcius, the user types it and the function
is called to convert this from Degrees C to Degrees F and display the

The result of these exercises will be posted later along with a functioning
program (except number 2 which requires an extensive coverage).

I hope the series on basics of functions was easy enough for you to
understand (and correct). If there are any mistakes, omissions,
misinformation and comments, please let me know (so that I can learn from it
and correct it)...
// JL P.S. Off to summer school at UCR...

Saturday, July 24, 2010

C++: more examples with functions

I think in order to understnad how functions works, it is crucial that we
try out some hands-on exercises with examples. But before the exercises,
here are quite a few more examples and notes. In this post, let us now
examine what happens if we write and call a regular function (those with
return type other than void).

First, let's consider a famous calculus problem: finding derivatives of
power functions. A derivative is the rate of change of a function over time,
usually denoted as F(x) prime or dy/dx. In our example, we want to calculate
the derivative of a power function (x^y) with the following algorithm, or
technically called specifications:
We want to return an integer value, so the return type would be an int. We
need two parameters: the function base, or f(x), and the exponent (^y),
denoted as base and power, respectively. We want to simply multiply the base
with power then return the multiple. For instance, if we want to find the
derivative of x^4, we would put 1 as base and 4 and power, then multiply
these two and return the result (4). The actual derivative is 4x^3.
Can you picture a possible problem? If you can picture it, I'll consider you
a genius (and perhaps add you as a Facebook friend...). But I will not touch
the problem yet, since the exercise here is to writing a functional
"function body." Then can do you have any idea on how you can help me
transform this English specs into C++?

The answer: the function signature, or the identifier that we use from a
host program to call this particular function goes something like this:
int derivative(int base, int power)
// The function signature with int as return type with arguments separated
by a comma.
int multiple; // The multiple of the base and power.
multiple = base * power; // The actual operation.
return (multiple);
Pay close attention to the "return (multiple);". This is the syntax that we
use when we are dealing with a function like this. in order for the host
program to process what we get here, the multiple must be used within a
method such as part of an output statement, or it needs to be assigned to
another integer variable. We'll see both examples in just a second.
Note: The derivative formula for power functions: multiply the base and
power and put this in front of the X, then bring the power down by one.

So, a more complete program which calculates a derivative is:
#include <iostream>
#include <string>
using namespace std;

// A function to calculate derivatives of power functions.
int derivative(int base, int power)
int multiple = base * power;
return (multiple);

// The actual program:
int main()
// a simple derivative calculator.
cout << "Welcome to Joslee's derivative calculator." << endl;
int func_base;
int func_power;
cout << "Please enter the base of your function:" << endl;
cin >> func_base;
cout << "Please enter the exponent of this function:" << endl;
cin >> func_power;
int dydx = derivative(func_base, func_power);
cout << "dy/dx " << func_base << "X^" << func_power << " = " dydx << "X^" <<
func_power-1 << endl;
return (0);
A bit complicated... But I'm sure you'll understand it better if I try this
program out:
Computer: Welcome to Joslee's derivative calculator.
Computer: Enter the function base:
Me: types "5".
Computer: Enter the exponent:
Me: types "3".
Computer: dy/dx 5X^3 = 15X^2.
Yes, and that's a bit better than writing the whole derivative operation in
the main() code.

As an added bonus, we can add conditional statements in our functions -
which allows me to answer the forseen problem of a user entering zero or 1
at the exponent prompt. To help us with this mess, we can add a useful
conditional statement (perhaps an if statement or two) to test whether the
entered value is zero or not. I cannot test for input of 1, as this
complicates matters worse (we need to create another function which is
called by the derivative function to sort this one out); right now, I don't
have enough time and space to try it out yet - perhaps next time. But the
point here was that we can do anything with a function, just like we can do
anything in main() (after all, main() is a function - a special one, after

Hope this gives you some picture of some basics in functions. There are more
things to be talked about, but I'll leave it up to more posts to do that. As
for what's ahead, I'm not even half way through - I still need to talk about
member functions, passing by value versus by reference and so on...

note: A member function is an action (or a function) that can be done with
that particular data type (technically an object). For instance, if we have
a vector and if we want to add new values, we can use push_back member
function under vector object (data) to do that. A member function has a form
of data.function where "data" is the actual data type that we are working
in, and the "function" is the member function of that data. So, in tech
language, the push_back is a member function (or a member) of vector object.
We'll come back to the notion of member functions much later when we talk
about designing our own data types.

P.S. Actually, under void functions, you can have a return statement like

I think that's enough for now. I'll come back with more practices with
functions. Again, if the content was not simple (or incorrect) for people to
understand, I apologize. As always, feel free to comment this post and
// JL P.S. Most of the notes come from CS010 class and various books.

C++: Functions continued...

On our last post, we've talked about what a function is and a basic
declaration of a function. Let's examine functions in more detail.

One of the properties of a function is its return type. This is used to tell
the program which calls the function as to what type of data are expected
from it. For example, if a function's return type is an int, the program
would expect the return value to be an integer so that the result of it can
be assigned to an integer variable. However, not all functions returns
something. There is a special return type called "void" which means that we
want our function to do something instead of returning a result, called a

For instance, suppose if I want my function to get my name and age and
display it to the screen. Since we are not looking for a particular value,
this can be written as a procedure - using void as its return type.
The algorithm in English looks like this: I just want to get this function
to capture my name and age then display to the monitor. We don't need any
arguments, since we are just dealing with a procedure (however, sometimes an
argument is needed for a void function as well). The function would ask me
for my name and age (separately, of course), then it should print out the
values entered.
Before we continue with C++ version, let's examine this procedure in more
detail. The first question you'll ask is, "how would this blind guy give his
name and age to a function?" The answer is almost like using the method
we've known so far: using main() function. however, instead of writing the
whole procedure in main(), I can write what needs to go into main() in this
small function (creating variables, inputs and outputs and so forth).
Secondly, you may ask, "how come this dude didn't say anything about return
value?" Logically, if the function is a procedure, we don't need anything to
pass back (return) to the calling program, right? Now I think you can
envision the C++ version of this function...
// A function to capture my name and age then displaying it on a monitor.
void my_intro()
cout << "What is your name?" << endl;
string name; // My name.
cin >> name;
cout << "What is your age?" << endl;
int age; // My age.
cin >> age;
cout << "I am " << name << ". I am " << age << " years old." << endl;
Now, let's write and call this function in a test program:
#include <iostream>
#include <string>
using namespace std;
// A program for testing a small functio...

// A function to ask my name and age then printing it on a monitor.
void my_intro()
cout << "What is your name?" << endl;
string name; // My name.
cin >> name;
cout << "What is your age?" << endl;
int age; // My age.
cin >> age;
cout << "I am " << name << ". I am " << age << " years old." << endl;

int main()
// Call the intro function...

return (0);

Very simple, huh? If we do compile this program and run it, we'll get:
Computer: What's your name?
Me: types "Joseph".
Computer: What's your age?
Me: types "20".
Computer: Hi, I am Joseph. I am 20 years old.
Well, how about that? We didn't have to write the actual function body in
our main() function - this saves a lot of space and looks more neat too.

One last thing on this post: Have you noticed that I used braces to mark
that it's a body of a function? I've already mentioned a basic info about
this, but I think this is the first time you are seeing this in its true
form. The braces ({}), as described earlier, is used to denote that we are
in a block of a program. in this context, whenever we run or call a
function, the code from the function (those within the braces) temporarily
takes over, and when we are done with it, control is passed back to the
program which called the function in the first place. As a side effect, we
can call another function from within a function - so that the newer
function takes control from the current function, and when it is done, it
passes control back to the function that called it, which in turn passes
back it's own information back to main(). sounds a bit complicated, but
you'll see this concept again when we work with objects and such. I've even
included a small exercise to illustrate a function calling another function
but you'll meet it later.

More to come later...
// JL P.S. Again, I know it was not easy explaining this stuff... sorry
about that...

C++: Program within a program: introductory notes on functions

When we think of functions, we think of various things. For mathematicians,
it means representing input and output, or describing a relationship. For
others, it may mean how something works, as in the phrase, "the DVD player
has functions to convert video to audio." For programmers and students who
are learning a programming language, functions has a surprising meaning: a
mini program that does something to perform a task. In this part, we'll dive
more into functions and how it works, as well as tricks and different types
of functions.

From the very beginning of our adventure, we've dealt with a function
already - the int main() function, which is the main program sequence. Also,
you may recall that I talked a lot about functions and gave you a preview
sort of notes in the post about vectors. In our context, a function is
defined as a "blackbox" that does whatever to help users use a program.
Functions may perform a wide range of tasks, including converting one unit
to another, calculating derivatives and series, playing a media file to even
closing a nonresponsive program.

There are different types of functions, including the int main() that we've
seen so far, a method (void) that does whatever without returning anything
and recursive functions which calls itself repeatedly. We'll meet these
advanced types later as we go through this "functional adventure."

To begin with, a function requires at least four things: a return type, the
name of the funciton, the argument and the actual return value. A return
type specifies what the resulting value would be when we are done with a
function. The function name is the one that we'll use in our program to
call, or instruct this function to do something when required (the signature
of a function, sort of). An argument is just data that a function will use
to process something. A return value is the actual result of a function that
the "host" program needs.

For example, suppose if we are writing a function to convert from kilometers
to miles. The required things would be: a return type, which in this case
would be a decimal number, the name of the function (let's call it km2mi),
the argument - in our case, the kilometer value and the actual value that
should be returned after the conversion is done. In English terms, the
function would do the following:
Take the orignal kilometer value as the parameter, or the argument. Then
using this value, convert this value to miles (km times 1.6). Then return
this new mile value (a decimal value) to our program.
Sounds complicated, isn't it? But when we do translate this into C++, it
makes more sense (at least for me). Let's see if you can grasp the
translation from English to C++:
// A function to convert from kilometers to miles:
double km2mi)int km)
return (km * 1.6);
Ah, seems interesting. We've just did our conversion in the return statement
(multiplying the argument by 1.6). This is just a short function, just to
convert from one unit to another, as you've seen from our English

To better understand what I am saying, I think it's appropriate to plug this
function to a test program:
// A unit converter...
#include <iostream>
#include <string>
using namespace std;

int main()
// Convert from KM to miles.
int km; // The kilometer value.
double mi; // Mile value.
cout << "Enter distance in kilometers:" << endl;
cin >> km;
mile = km2mi(km);
cout << km <, " kilometers = " << mile << " miles." << endl;
return (0);

Please pay special attention to the line:
mile = km2mi(km);
The thing we are doing is called "calling a function," or invoking a
function to do our task. The function name is followed by parentheses with
the km argument inside. In our context, the variable "mile" is assigned to
the result, or the return value of our km2mi conversion function.

I think this would give you at least how a function's syntax looks like. In
the following posts, I'll go into different types of return type, methods
versus functions and why we use braces ({}) to surround the body of a
function. In addition, I'll give you advice (at least what my professor
taught me) about function length, using function signatures and so forth -
to lay the foundational knowledge for future adventures.

P.S. If you find that this post is hard to understand, I apologize. If you
have comments, please let me know.
// JL