## 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)...
http://hanopolis.com/?articleNo=29799&story/UC-Riverside-student-crowned-201
0-Miss-Korea

// 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.

// 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

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
happens.

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
screen.
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
above.
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
sheet.
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
items?
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
loop?
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
post.

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:
v.pop_back();
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):
Item.pop_back();
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
vectors.

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
English):
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
variable):
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:
Text.find("g");
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 cplusplus.com) 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...

Hi,
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

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
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
function.

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
practice.

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
result.

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;
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
all).

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
return;

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
others.
// 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
procedure.

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...
my_intro();

return (0);
}

Very simple, huh? If we do compile this program and run it, we'll get:
Me: types "Joseph".
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

### 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

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
explanation.

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
// JL

### C++: Introduction to vectors

Personally, I felt that last post was a bit of a departure from what we've
thought of as declaring a variable - we were talking about arrays. This
time, it is yet another departure from what we were used to working with
data, and that's vectors.

A vector is a group of related data, like an array. But unlike arrays,
vectors allows us to resize it, add more items or removes ones from the end
of it and so forth. It has other goodies, such as finding out how many items
are on a vector, looking up the first and last element of it and so forth
via functions. Now why am I mentioning this? Because vectors are an example
of a data type that uses functions a lot, which will be the next grand march
after vector operations are covered.

In this post, I'll not expose you to inner workings of how vectors work and
what kind of useful functions are availible to work with it. That discussion
is reserved for somewhere else, and that is when we are designing our own
vector class as a practice exercise later. For now, I'll go over how to
declare a vector, add a new item and how to display it using several
functions (which I think would provide a gentler intro to functions).

First, before we even declare a vector, we need to include a new library,
logically called vector. So whenever we work with it, at the top of our
program file (.cpp), we need to write:
#include <vector>
This allows us to work with vectors and utilize functions associated with
it. Then to declare a vector, we would write:
vector<type> vector_name;
where "type" is the data type that a vector would hold. For example, if we
want to work with a series of strings, we would write:
vector<string> string_vec; // A vector of strings.
This creates a sufficiently large vector to hold about several string data.
There are a number of variations of the above declaration, including
provision for telling the program how many data we need to use, as well as
setting each data to a default value. For example, if we want to work with
ten integers stored in a vector, we would say:
vector<int> my_integers (10); // A vector with ten ntegers.
And if we want to go further and assign zero to each of the integer entries,
we can write:
vector<int> my_integers (10, 0);
The first variant just sets up a vector array with ten spaces to be filled
in (actually, they are set to a predetermined value); the number of items
must go inside the parenthesis. The second version goes further and declares
that we want to fill ten spaces with 0's, with each argument separated by a
comma. I'll describe how this magic is performed much later.

Now we have our vector, how do we know the size of it? We can use a helper
assistant to tell us how many items are in a vector (this is called a member
function, which I'll go over later). For example, if we want to find out how
many items are there on my_integers vector, we can write:
my_integers.size();
The syntax above is the default form where the variable name is followed by
a dot (period), then the function name. So, using the example above, if we
use this code in our program, it should tell us that there are ten items.

Now, how to we add additional items to our vector? You may recall that
arrays does not allow its size to be changed by adding new items; in
vectors, we can by using another member function called push_back. This one
alloows us to add additional item by putting the actual item within
parenthesis, like this:
my_integers.push_back(11);
In other words, we have just added a new item, 11 as our eleventh item in
our my_integers vector.

Now, how about if we want to display items in this vector? Just like arrays,
items in a vector can be accessed using the subscript operator ([]). Also,
note that we can use a "for" loop to display the vector items. A rough
English version is this:
First, we want to set up a for loop so that it would print from the
beginning of a vector until all items were printed. Thanksfully, we do know
how many items are there in our vector via size() funciton, so we can use
that as our termination indicator. Then we can increment our output by one
until everything is displayed.
In C++, it would go something like this:
// A complete program to print out a vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// First, get some numbers to be stored on an integer vector.
// Let's create a vector with five elements, all initialized to the value
10.
vector<int> ten (5, 10);
// Let's display the vector.
for (int i = 0; i < ten.size(); i++)
{
cout << ten[i] << " ";
}
cout << endl;
return (0);
}
Quite a review here. We've noted that we can use the size function to find
out how many elements does a vector have, then we can use subscript operator
to access each element. If we run this program, it would print the value 10
five times.

The reason why I'm stopping the discussion of vectors here is that most of
our notes here refer to something we haven't covered extensively. This is
functions, which I'll talk about next.
// JL

### C++: arrays and Vector basics

Starting from this point on, I'll be using a lot of tech terms in
programming, along with terms that you've never seen before or the ones that
have different meaning in C++. But because of the nature of these notes,
I'll try my best to be friendly when explaining those terms. The first of
these is what's called arrays and vectors, which are used to store a group
of related data as a single package.

An array is a contiguous data. In layman's terms, it's a "line" of data as
though one data follows another, like a train. To help us identify the
actual data we are working with, a new concept of an index will be used. An
index is the location where the actual data resides. For instance, in a set
of even numbers from 2 to 10 (2, 4, 6, 8, 10), the fourth index would house
the number 8.

Here are few things you need to know about arrays: To declare an array, we
need not only the type of data we'll be using, but also the number of such
data we'll need. For instance, if we want to declare an integer variable to
store five even numbers from 2 to 10, we would write:
int even_numbers[5] = {2, 4, 6, 8, 10};
There are quite a few things we haven't seen before. The square brackets
([]) is read as subscript operator. So if we want to declare any data type
with any number of them, we would put the number of data within square
brackets. The one after the assignment operator would be the contents of
that array, enclosed in curly braces ({}) and each of them separated by a
comma.

There are other ways of declaring such variables. One of the popular ways is
using the following:
char characters[] = {"a", "b"};
Notice that we didn't say anything about the number of items within the
brackets. However, when we compile this code, the compiler would know that
we've just declared an array of two characters, namely A and B. So, in our
case, both
char characters[2] = {"a", "b"};
and
char characters[] = {"a", "b"};
are perfectly valid.

To access an item in an array, we need a special concept we've discussed a
bit earlier: using 0-based indexing. So the first item in an array would
have index of zero, followed by index of one, two, and so forth. The problem
here is that arrays, unlike vectors which I'll describe a bit later, does
not allow you to resize it i.e. does not allow you to change its size,
although it is possible to change what's stored on it using its index.

For instance, using the even number array above, if you want to change the
fifth item from 10 to 12, we can do something like this: First, create an
integer variable named "i" to store index locations. Then set this variable
to 4 (the fifth element); as you have noticed, we need to put 4, not 5. Then
assign 12 to the value stored on the fifth index (index 4).
In C++, this is done like this:
int i; // The index.
i = 4; // Assign the index location to 4 to access the fifth element.
even_number[i] = 12;
At least for now. There are other ways of doing it, but because of time and
space, we'll leave it at that.

Well, at least that's the basics of arrays. In the next installment, I'll
introduce you to so-called vectors, and enhancement of arrays. After
vectors, we'll get into the basic foundation of "reusable code of
convenience" - functions.
// JL

### Hardware tour: about storage sizes and different number bases

Let's go over storage sizes and how computers and us (users) deal with
numbers.

Recall that I've mentioned a counting program which displays numbers from 1
to 10. You may also recall that i wrote two versions of this program - first
initializing "i" to zero then reinitializing "i" to one, and I said I'll
come back to a more detailed discussion on it. The reason why I brought this
up is because computers use zero-based indexing (counting from zero up) when
dealing with almost everything - from storage size to counting, unlike us
using one-based indexing. This becomes important as we tackle arrays (a
group of same data type) - arrays and such start counting their index at
zero, not one. So the first data in an array is indexed zero, then one, two,
etc. as opposed to how we would count it - first, second, etc.

As for storage sizes: there are many prefixes that computers and users use
to identify the size of something. To start with, a byte (a character) is
eight bits (binary digit). Also, people use ten-based counting (decimal)
when talking about size, whereas computers use two-based counting (binary).
So, a kilobyte, or about 1000 characters, would be a thousand characters
when spoken by users. Computers, on the other hand, treats a kilobyte (KB)
as 1024 bytes (2 to the 10th power).

Here are some prefixes when talking about different size of things:
* A byte: eight bits.
* Kilobyte (KB): 1000 characters versus 1024 bytes.
* megabyte (MB): 1 million characters versus 1048576 bytes (2^20).
* Gigabyte (GB): 1 billion characters versus 1073741824 bytes (2^30).
* Terabyte (TB): 1 trillion characters versus about 1.099*10^12 (2^40).
As you can see, the differences become pronounced as size increases.

One last thing: there are more number bases besides decimal (base 10). In
fact, we can count anything using any number base. Some of the well known
ones include decimal, binary (base 2), octal (base 8) and hexadecimal (base
16). For example, the number 10 can be represented in other bases such as
1010 (binary), 12 (octal) and A (hexadecimal). Note: the decimal values from
10 to 15 under hexadecimal are represented by A through F.

Another example: suppose if we want to convert a hexadecimal value 3D to
other bases. The answer would be: 61 (decimal), 75 (octle) and 111101
(binary).

I guess that sums up hardware basics. Now, let's return to software
basics...
// JL

## Friday, July 23, 2010

### A slight detour...

By now you should have at least basics in how to write a small program - at
least a small game, perhaps. But computers are not just based on software -
they also work with hardware. In order to continue with more advanced
topics, I think it's time to go over some hardware basics. Along the way,
I'll introduce you to some basic things that computer science and
engineering studetns learn about the subject at hand. let's begin by
examinng the history behind computers.

Our discussion starts with a very word that we use everyday: a computer.
Historically, a computer meant a person who keeps track of records or an
individual who was very good at calculations. In modern sense, a computer is
a device that stores, retrieves and processes information. This could be
text files, multimedia applications and even keeping track of sattellites on
space. In simple terms, computers can be thought of as a large calculator
that works with numbers, text commands and so forth (mostly because early
computers were based on calculators).

The first computers appeared around mid-1940's with the development of
ENIAC, a large electronic computer used for large calculations. Mostly these
were used in military and research labs for decoding enemy codes and so
forth.--Source: Wikipedia article on computers. Since then, numerous
advancements allowed engineers to develop smaller yet faster computers and
using punched cards, tape drives and other means of storing information.
Later, with the development of Arpanet (a modern grandfather of Internet),
communication between computers became practical, thus what we now call
internet was born. These days, computers are a lot smaller, faster and ever
connected to the Internet thanks to advances in processor technology, more
secure memory and wireless means of communicating with others.

There are numerous types of computers. They vary in size, speed and intended
use. The top of the line computers in the world are called "supercomputes,"
designed for processing huge number of information at once, such as weather
forecasts, game engines for chess and so on. Then there are minicomputers,
then finally what we call computers, or more technically called
microcomputers. Still, there are specialized computers such as embedded
computers, computers designed for special tasks e.g. network routers, kiosks
and so forth and others. Even cell phones are computers themselves - a
special computer which allows people to send and receive calls, communicate
via text messages and so forth.

So how are these terms interconnected? Computers, or computer systems, are
organized into various layers, including software, hardware, operating
system and so forth. Let's examine these layer in more detail.

A computer hardware is the physical characteristics of a computer. This
includes computer case, processor, memory, disks and other devices such as
sound cards and network ports. A processor, or so-called Central Processing
Unit (CPU) is responsible for carrying out instructions for a computer
system, such as getting new commands, process it, output it and get another
instruction (a series of commands for a CPU to perform). The memory is used
to store running programs and files that a software (program) needs to work
with. there are numerous kinds of memory, including RAM (Random-Access
Memory) which is used as a temporary storage, hard disks (a magnetic disk
used to store files and folders even when the computer is off) and optical
discs such as CD's DVD's and blueray Discs (BD). These are called primary
(RAM) and secondary storage, respectively. I'll talk more on that later when
i discuss memory types. Other peripherals perform specialized functions,
including allowing a computer to connect to the Internet, processing sounds
and so forth.

However, computer systems are not just limited to the hardware above - there
are other devices that needs to work together with a computer to allow users
to work with it. These include keyboards, mouse, monitors, printers and so
forth. These are collectively called "input/output devices", or I/O
peripherals. I'll discuss more on this concept when we get into file
operations.

Before we end, let's discuss different memory types that a computer use to
process data. As discussed above, there are numerous storage options
availible, including physical memory (RAM), hard disks and so forth. The RAM
is used to store running programs and data that these programs use, such as
audio files, documents, spreadsheets and files to be checked by antivirus
programs (yep, computers are vulnerable too), as such, it is known as
primary storage device. However, there is one huge disadvantage: Even though
RAM (Random-Access memory) is faster than hard disk, RAM stores information
only when computers are turned on, so when power is off, anything that is
stored on RAM is gone; this is called volatile memory. I'll come back to RAM
and its organization much later when I go over pointers and so-called memory

As opposed to drawbacks of RAM, a secondary storage device, such as hard
disks, CD's and so on are used to store programs and files even when
computers are turned off - logically enough, it is called nonvolatile
memory. A hard disks use magnet coded disks (on a disk platter) for storing
information, hence they are called mechanical. This allows many characters,
or bytes of information to be stored on these disks. An optical media, such
as CD's store information on a specially coded plastic discs, and a newer
memory type called flash memory uses electronic cells to store data.

In the next post, I'll discuss more about storage capacity and the meaning
behind my previous statement about different CPU's knowing their own machine
language.
// JL

## Thursday, July 22, 2010

### C++: Intermission 2...

For me, I struggled with for loop when I first learned it. This was way
different from what I used to do - doing a while loop. Not until last year
when I did an introductory course I came to the conclusion that for loop is
essentially an enhancement of if and while loop.

Another thing that I was confused about was the difference between a while
and a do-while loop. I knew that do-while was somewhat different from a
while loop. One day, I saw a post from a mailing list for blind programmers
which clarified the difference between these two. The post in question was
in response to a question from a beginning C++ student about the while and
do-while loop. According to the post, the while loop checks the condition at
the beginning to determine whether to run the while loop, whereas the
do-while requires checking conditions at the end i.e. a code that runs at
least once before continuing with another repetition.

Also, a general advice: if your program specs require that you run a part of
your program for a certain number of times, try picturing a for loop
(technically called iteration). There is a more advanced form called
recurssieve function calls where a function would call itself multiple times
until a base case is reached. It is perfectly fine to convert from iteration
to recurssive function calls and vice versa - but note that recursive
functions take up more storage space and takes longer to print out its
results (which is the perfect setting for me to go into hardware). We won't
go into recursive functions yet - both because it's so advanced and the fact
that I didn't really grasp the concept about it fully yet- this is one of

Well, hope you are enjoying this series. On the next section, we'll take a
detour and investigate about hardware basics before continuing our journey
with arrays and vectors. If you have any comments, please let me know via
email, Blogger comment form or on my Facebook page...
// JL (UCR)

### C++: Misc items 2

I haven't forgotten about other stuff which I should mention before I
continue...

An alternative to "if" statement is "switch" statement. This is useful if
you want to incorporate a menu-like system where a user presses a command
and it would automatically execute a part of the program. A conventional
syntax is:
{
case 1:
// Field 1.
break;

case 2:
// Anything else...
break;

...
default:
// A default message...
}
At the first glance, this sounds more like English...

As previously mentioned, it is perfectly possible to have nested loops -
even within for loops. But how does a program know what portion of the loop
to run? It looks for the inner of the loops to run before continuing with
the rest of the outer loop. For example, if I have a for loop inside a while
loop, the computer would run the for loop first, then check the condition to
whether repeat the while loop or not. This is called "scope," which we'll
talk more about when we get into functions.

Speaking of while loops, we can have a variation known as "do-while" loop.
This is useful if you want to run the code that normally belongs to the
while loop first before testing the condition. An example would be a
guessing game where the user would be prompted if the input number is higher
or lower than the guess that the computer had in mind (this was one of my
lab assignments to check for segmentation fault). A typical code might be:
do
{
// Whatever the program does...
} while (the condition);
In other words, we are checking the condition at the end, as opposed to the
while loop which checks the condition first.

//JL

### C++: A more realistic set of problems

So far, we've discussed ways in which we can change the flow of execution,
or branch into scenarios based on conditional statements. Also, we've
learned that we can have a part of our program run repeatedly as long as the
condition is right. now, let's put that into practice...

1. You want to buy a friend of yours a gift card on his birthday. The
problem is that he was born on February 29, 1988 - a leap year. To help you
keep track with this problem, you've decided to write a program that checks
whether the year that you've typed is a leap year or not. A leap year is a
year divisible by four unless it is also divisible by 400. For example, the
years 1600, 2000 and 2400, as well as 1996, 2004 and 2012 are leap years.
The years 1500, 1700, 1800, 1900, 2100, etc. are not. Can you come up with a
possible algorithm to solve this dilemma?

2. now, with your algorithm at hand, write a small program to check leap
years: first, try using an if statement, then try writing a program that
keeps asking you to enter a year, output whether it is a leap year or not
until you press 0. Compile after each set and notice the differences (hint:
one is a loop).

3. An elementary school child (perhaps a first grader) asks you if you can
teach her about multiplication table. You asked her how it should be done,
and the child asks you to give her a small toy that will tell her the
multiple of a number from 1 to 10 - for example, a base of three would tell
her numbers from 3 to 30. So you decided to write a small program that you
can put in this toy so that the child can play with it. What will you do to
solve this problem? (hint: we want a for loop to help us out). Write the
English version of your "code", then write your code based on your
algorithms and explain (in comments) as to how this program would run.

The answers and an example program set for each of them will be "offered"
later.
// JL

### C++: Limited Time offer with "for" loop

No, I'm not advertising a cool product here... If I did, I would tell you
and perhaps announce it somewhere else. The title is just a humor on a topic
for this post: the "for" loop.

The for loop is a special case that requires extensive coverage. It behaves
somewhat like a while loop but it has numerous twists. First, we have to set
three things or less: the starting value, the termination value and an
incrementor. The starting value, or index is where the for loop begins. The
termination index is the value that tells the program that we are done with
the loop. The incrementor is meant to tell the program the course of this
loop e.g. move step-by-step or increment by 1. I know this is somewhat hard
to explain - I was in that position when I first learned for loop.

The English version of the syntax is:
for (StartIndex; TerminationIndex; Incrementor)
{
// Do whatever...
}
The more generalized C++ example is:
for (int i = 0; i < whatever; i++)
{
// The content of the loop...
}

For instance, suppose if we want to have the program print out numbers
between 1 and 10 in sequence i.e. one by one, we can do this: first, set the
initial value to 0. Next, set the ending value to 10 and have the loop
operate until the value reaches ten. Then increment this loop step-by-step
i.e. one by one. The content of the loop (between braces) would be the
output code. Let's see how this can be translated into C++:
#include <iostream> #include <string> // The usual code to include iostream
and string.
using namespace std;
int main(); // The start of our program (int main();).
{
// The for loop to print numbers from 1 to 10:
for (int i = 0; i < 10; i++)
{
cout << i+1 <, " ";
}
cout << endl;
return (0);}

If we compile this program and run it, we get:
1 2 3 4 5 6 7 8 9 10

There is a reason why I didn't declare any int variables on the main block:
that variable is declared as part of the for loop declaration, and we want
to just add 1 inside the loop to print the correct number. Alternatively, I
could have done this task using more familiar way, as in the following
description and code:
// An alternative way...
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
}
cout << endl;
Notice that we have started counting at 1, which is in keeping with more
common sense terms. Also, you might recognize that we end our loop when the
count reaches 10 (as evidenced by less-than or equal to operator). In other
words, we can start at wherever we want and terminate it whenever we are
finished with it. But for general practice, I personally suggest that you
use zero (0) as the starting point.

As an additional trick, we can ask our computers to check whether the first
entry of the for loop is right or not. If the entry is not what the computer
is looking for, we can ask the user to type it again. if the entry is
correct, then we can continue running for loop. This uses all conditional
statements we've looked at so far - if, while and for. One of the review
exercises later will ask you to try out this problem.

As we have seen, the for loop is used to repeatedly execute a program a
number of times before continuing with our next step. I'll come back to for
loop later when we discuss arrays and vectors - how to store additional data
and print what we have in there.

P.S. There is a reason why I brought up counting problem. I'll discuss this
as part of our detour into hardware stuff after the review exercises.

### C++: A review exercise

A review exercise to go over what we've seen so far:

want students to type a number and have the computer say whether it's and
odd or an even number. This would be done repeatedly until a student types
negative 1. Do you have any idea how it can be done? Please help me do it
both in English and in a programming language.

JL: Actually, I do know how it can be done, but i will not tell you now -
the answer will be provided later. Few hints though: try using a variable
and try testing the input number. Also, you might want to try out modulus
operator for one of its tasks - tell me where and I'll write you a comment
// JL

### C++: while loop - repeating certain part of a program

So far, we have worked with so-called "procedural" or linear programs where
the program runs from beginning to end. But what if we want to repeat
certain section (a block) of a program until a condition is met? The answer
is that is perfectly possible. This algorithm (precise steps) is called a
loop ( circle, perhaps). There are many ways of achieving this, including
setting a defining condition so that the program runs repeatedly until this
condition is met, or run a block of a program for a certain number of times
before continueing with the rest of the code. What I've just described are
called "while" and "for" loops, respectively, but in this post, let's go
over the simplest one first: the while loop.

A while loop, as described earlier, means that a computer will run a section
of a program repeatedly until a certain condition is met. For example,
suppose if we are to write a number guessing game with a fixed number as the
guess. We could describe the algorithm as:
First, display the prompt so that a user can write guesses. Then have the
user enter the guess. If the entered guess is not what the program is
looking for, tell the user to write the guess again. Repeat the last step
until the correct guess has been entered.

Do you have any idea on how to convert this into something we can use in
writing this sort of program? As it turns out, the while loop consists of
only seven to ten lines of code: (code from C++ A Dialog by Steve heller
with my modification):
// The usual start of a program that includes iostream and string.
// The program starts (int main();).
cout << ""Enter a guess between 0 and 9:" << endl;
int guess = 4;
int number;
cin >> number;
while (guess != number)
{
cout << "Huh? You typed a wrong number. Try again:" << endl;
cin >> number;
}
cout << "You are correct!" << endl;

Few notes to consider: you might have guessed that the actual while
statement tests whether a number entered is the same as the guess value (4)
and runs the block if it is not. Also, you might have noticed that I wrote
two input statements, one right before the loop and another within the loop.
Can you guess as to why is was done like that? The answer: as in common
sense, we need to test what we are actually testing to see if we are right
or wrong - in this case, we are testing the value that the user enters in
the beginning. If the user enters the right value, this is great - we don't
have to enter the loop (I consider you a genius). However, the objective
here is, "what if the user types wrong value in the beginning," thus we had
a provision for having the while statement. Also, at the end of the while
loop, we had to ask because we want to make a decision to enter the loop
when a user types the wrong number, thus repeating the process over again.
Hope you understand this, as this notion of a loop becomes important as we
continue with for loop later.

Using wile loop, we can perform all sorts of conditional repetetive tasks,
including guessing games, getting a number of user input to be processed
later (via functions) and displaying the contents of a file (file
input/output, or I/O will be discussed much later). As for conditions, we
can have all sorts of them, including checking whether a user typed correct
number or a letter, provide provission for continued execution of a program
to even ending a loop. An example is getting two or more numbers, provided
that the second number onwards is greater than zero, or typing "-1" to quit
a program, as in case of some of my first assignments with while loops.

But be careful with loops though: Have you wondered why some programs never
terminate with our without displaying something to the user, requiring
to a well-known "bug" called an "infinite loop" i.e. a loop procedure that
never ends. This, according to what I read and experiences , is mostly
caused by a loop that doesn't have conditional statement, or a loop that has
a nested ones of their own (logicaly called nested loops) without a clear
way of terminating it. For example, what if our guessing game code above
didn't have a clear condition i.e. the actual number to terminate the loop?
The result is that the program will ask you SO MANY TIMES(in a never ending
cycle) to ask you to type in a number to be guessed. Also, if a program
eats, or allocates memory during while loop without ending it, we could run
into a potential problem called "memory leak." The only way to end this sort
of program is using intervention from an operating system, such as Task
manager or typing CTRL+C under Windows/Command Prompt. P.S. The concept of
memory leak will be discussed in more detail when i post notes on working
with dynamic memory allocation.

Now, I guess it's time for a fun exercise (maybe to help you get started
with while loops): suppose if we want a user to type a letter and see if it
matches the command that the computer is looking for. for this one, let's
ask the user to type a letter. If the letter is "J", let the computer say,
"Jackpot," otherwise let the user type a letter again. Sounds a bit
complicated this time, but I'm sure we can do it. But there is a provision:
you need to do it; but I'll give you some hints:
1. You might want to create a character variable to store your guesses. For
now, initialize (or assign) this variable to the letter "J".
2. Try out an "if" statement first and put the condition so that when the
user types "J", the computer would print out, "Jackpot," otherwise print
"Huh, what are you saying?".
3. This time, try out the while loop version with a condition that the
letter is not equal to "J". If that's the case, have the computer print out,
"Huh, try again. There is a letter I'm looking for." If the user types "J",
say, "Jackpot!".
4. Try compiling your results (twice, one after writing the if version and
once more after replacing the if with while). Do you see any differences?
The answer to this quiz (at least how I would do it, along with an example
program that you can download (if possible)) will be posted at the end of
this section (not this post, but later).

Postscript: As it turns out, there is a variation of our while loop
statement: the "do-while" loop, which means that we want to run the code
within the while loop at least once before continuing with the looping
process. I'll discuss the difference between "while" and "do-while" in more
detail later when I have time with an example of a more complete guessing
game program. But just for sake of our discussion, think of while loop as an
enhanced version of "if" statement that checks the condition first (in the
beginning) before entering the loop, whereas the "do-while" first runs the
loop (like the program) and checks the condition at the end to determine
whether to continue or not.

Next: An exercise...
// JL

## Wednesday, July 21, 2010

### C++: the "if" statement - helping computers make decisions

How can we have a different response from a computer if we type something?
How can we allow a computer to distinguish between negative and positive
numbers? It all comes down to two words: conditonal statements. In this
context, a "conditional statement' is the code that allows a computer to run
part of a program that correspond to that particular condition. For
instance, if we ask our computers to tell us if a number is odd or even, it
would give different responses (run different parts of a program) depending
on if we type odd or even numbers.

The starting point of our discussion begins with the word "if". We ask all
sorts of questions with the word "if". For instance, we would ponder, "if I
eat now, I won't get hungry," or "if I fix a bug in a program, a new bug
would emerge." The second question would be more relevant here, since we are
dealing with a silicon chip to do our bidding (I personally call it
"fighting between myself and my computer"). C++ is not an exception (well,
if we say so), and the word "if" is used as a keyword to denote conditional
statement.

For example, suppose if we want to see if a person is allowed to vote based
on his or her age. A psudo code (the English version) would look like:
First, declare an integer variable called "user_age." Then have the user
enter his or her age. if the age is 18 or older, tell the user that he or
she is eligible to vote (Source: 26th amendment to the United States
Constitution). If not, tell the user that he or she is not eligible.
This is called an algorithm - a precise way of doing things to perform a
task. The thing to be evaluated is the user's age and the condition is if
the number is above or equal to 18 or not.

Can you guess how this is done in C++? it would look something like this:
// The program to test user's age for vote eligibility.
int user_age; // The age of the user.
cin >. user_age;
// Now, the conditional statement...
// If the age is older or equal to 18:
if (user_age >= 18)
{
cout << "You are eligible to vote." << endl;}
// If not...
else
{
cout << "Sorry, you cannot vote." << endl;}

Notice what we have here - almost the same as English version. First, the
program asks the user to type his or her age. Depending on the number the
user typed, it would display the first message if the age is greater-than or
equal (<=) to 18, otherwise it would print out the second message. We only
need these two conditions since we are dealing with one condition - if a
number is greater than or equal to something or less than that.

So, according to syntax, an if statement would have an else statement. There
are variants of this, including testing for one than one condition or having
no 'else" statement at all in the middle (just bunch of if's before the
ending else). For instance, suppose if we ask the user to type a number and
tell the computer to print out different responses based on the following
conditions:
* If a number is positive, say, "Greater than jackpot."
* If the number is negative, say, "less than jackpot."
* If a user types zero (0), say, "jackpot!"
So, if we turn this into C++, a variant of the "voter age" code would come
out, something like:
// The Jackpot program to see if a user types zero or not.
// The usual question and input phase. For this one, we'll use an integer
called "user-guess".
if (user_guess < 0)
{
cout << "Well, less than jackpot." << endl;}
else if (user_guess > 0)
{
cout << "Well, more than jackpot." << endl;}
else
cout << "Jackpot!!!" << endl;

There are reasons why i wrote this kind of code. First, it is advisable to
put braces ({, }) when writing the portion of the code that will run when
that condition is met e.g. see the first two conditions. For one-liners like
the third condition, you don't really need to, but i think for clarity, try
using braces as you've seen (especially if you are using braille devices and
screen readers). Second, for more than one condition, put "else if" in front
of the subsequent conditions (exception being the last one, which you can
just put "else").

There is a slight variant of this code without the middle else statements,
like:
if (first condition)
{
// run the code associated with it.}
if (second condition)
{
// Run the associated code.}
if (subsequent condition)
{
// Run that portion of program.}
else
{
// Something entirely new...}
Or a variation of these three versions.

The conditional statements are used to "branch", or run a different segment
of a program based on a condition. There is another way of doing that which
is slightly more compatible with English way of writing conditions. This is
called "switch" statement, which is another form of if using cases. But for
sake of space and time, I will not go over this one in detail - I'll mention
it towards the end, as the switch statement is related to the next topic...
// JL

### C++: Intermission 1 - my first programs...

As a gesture of humor and to ease your stress in learning programming
(mostly from blindness perspective), I plan to share my own thoughts and
experiences as an apprentice programmer/student.

My very first program, apart from Hello World, was a unit converter
calculator. This program would convert between different units, including
length, temperature and so forth. This was a fun experiment that taught me
more about operator precedence, variable assignment and so forth.

Then came one of the first programming assignment from UCR: a madlib Story
Writer. Our instructor, Kris, asked us to write a madlib program - a text
story with certain fields, such as verbs left out. Since I was familiar with
this sort of thing (I used to see), I thought of creating a text file with a
story of my own, then leave out various words (mostly nouns and verbs) and
turn it into variables (strings). After assigning variables, I would put the
variables as part of the output. Then I would ask the user to write things
like nouns and verbs; using this information, I would "fill in the blank"
with user input, then display the output.

Back then, it was a program that span no more than fourty or fifty lines of
code. But as Kris taught us more "tricks' with C++, it became clear to me
that many programs, including Microsoft Outlook which I am using to compose
this email post, would have had hundreds and thousands of olines of code.
Then i asked myself, "how could this be possible?" The answer was dividing a
program into multiple files, or modules via functions (functions will be
covered later) and reusing parts of existing code.

This allows me to introduce the file extensions of some of the files you'll
be making, which are .cpp (C++ source code), .exe (executable, or a
program), .h (header file which will be used extensively later) and .o or
.obj (object files that a linker will use to produce the machine code).

For beginners: don't worry about all sorts of stress - I've been there too.
help you out, so that when you see a similar person, you can help him or her
out.

feel free to comment on my blog posts.
Sources used: "Practical C++ Programming" from O'Reilly books, "C++ A
Dialog" from Steve heller.
// JL (UCR)

### C++: Misc notes from part 1

Few misc things...

There is something called "operator precedence" that you need to know. In
this scheme , certain operators, such as parentheses and * and so on has
higher priority, or precedence from other operators. sounds familiar? Right
from mathematics - you do multiplication before doing addition, and you do
things in parenthesis before anything else. You'll encounter this much
later.

The reason why I left out descriptions of comparison signs (less-than,
greater-than, etc.) was mostly because these are used for comparisons, as in
the case of conditional statements. Also, the double ampersands (&&) and
double pipes (||) are left out because they have special meanings later
9double ampersands means the left and right side is true (this and that),
while two pipes means one or the other (this or that)). We'll see the real
role of ampersand much later when we go into pointers. Speaking of pointers,
I have deliberately mentioned this briefly but left this one out. But you'll
see its march around memory fights later when we discuss it fully.

// JL

### C++: A review and a small exercise

As we wrap up the basics and prepare to move on, I thought I should briefly
summarize what we've discussed so far and perhaps provide a challenge to

In this saga, we have learned that a computer program is just a series of
instructions that a computer must carry out. Because computers knows their
own machine code, the source code, or human readable language code must be
translated, or compiled before we can view our results.

We've also learned that a data is used to store items, such as a characer,
decimal numbers or even true or false values. We also saw that we can output
informaiton, as well as get user input and store, then work with it using
various operators to help us with our programs. In addition, we have seen
how it is crucial to comment one's code, as well as some interesting notes
on the difference between assignment operator (=) and "is" operator (==).

So, here's the challenge: Suppose if you are working at a chemistry lab and
one of your friend, a research assistant asks you to help her with
converting temperatures from celcius to kelvin (after Lord Kelvin, a
standard way of displaying temperatures of chemicals). You ask her how she
wants it done, so your friend told you to have a program ask the user the
temperature in celcius and print the result in Kelvin. Provide; A. how you
are going to tackle this problem and a brief summary of your program in
English, then B. Write a code that uses your description to complete this
Hint: You might want to use two variables (decimal ones) and a famous
operator/formula to do this task. Details of how I would do it, as well as
an example program which can be downloaded (if possible) will be posted
// JL

### C++: Before we continue - viewing our coding results on the screen

Thanks to a comment from a reader, I've decided to write this small tip
before I continue with the next slide on conditional statements. The comment
says that I should write about compiling one's code to view it on a computer
screen, which is something I need to really get you going before I continue.

Before we view our results on a computer monitor, we need to perform what's
called "compiling." Compiling means translating a source code - the human
readable instructions to machine language so that a computer can work with
it. There are numerous processes involved, but the general breakdown is that
the source code is first translated into object files (a series of cryptic
messages and links). After this is done, a guy called linker comes up to
translate this object file into machine code. With the help of the
"librarian" or the standard template library, we get the final output - the
code that a computer can read and work with, called ironically, "machine
code."

But there is a huge problem: just like we (humans) speak different
languages, various computers, or processors (in this case) knows its own
machine language - thus there are so many languages for different CPu
(Central Processing Unit) family. In order to help us resolve a possible
dispute, we (the programmers and engineers) use different compilers for
different computers. For instance, the most popular processors in the
computers today are X86 and its derivative, X64 (from Intel and others) and
ARM for mobile devices, with each of these processors using different
machine language. Even programs which were designed for older processors
have difficulty "fitting" in with the newer guys - especially if we want to
use our programs on different computers. But for now, our chief concern is
"getting our code to be read by a computer," so, the role of choosing the
compiler that best fits you is importnat to get going with our code.

In my case, I use Microsoft Visual Studio 2008, an IDE (Integrated
Development Environment) which allows me to write and read C++ code,
translate it into machine language (compile) and view the results on a
computer monitor. There are other compilers and IDE's out there, including
MinGW, GCC (for Linux) and Borland 9a bit old compiler). For our further
tutorials and notes, I'll mention VS2008 a lot, but general instructions
apply to other programs of this kind.

One more note before I continue: A popular saying says that many programmers
spend majority of their time debugging, or correcting their existing code
than write new ones. Debugging means, in terms of literal meaning, "remove
bugs." In our case, it means finding what went wrong with our program and
find ways of fixing, or improving our software. (here, a "bug' is a problem
with a program). I'll frequently use the terms "debugging" or "debug" to
note that we need to solve problems with our program before continuing,
especially as we go to later part of this C++ saga. (Just a note: compilers
have facilities to allow programmers to debug our code, such as Visual
Studio's Just in Time Debugger, GCC's debug switch and so forth..

Before i close this message, here are some keyboard shortcuts for Visual
studio users:
* To compile your code, press F7.
* To run your program, press F5.
* Press CTRL+TAB or CTRL+Shift+TAB to move between windows or source code
editor windows.

At least that's the end of the basics in C++. Starting from next post, I'll
discuss ways in which we can allow computers to have "some intelligence".
// JL

## Sunday, July 18, 2010

### C++: An overview of operators

Suppose if we were asked to create a temperature converter that will convert
between Fahrenheit (degrees F) and Celcius (degrees C). The formula is:
Degrees F = -40 + (1.8 * degrees C)
Degrees C = -40 + (0.45 times degrees F)
So, zero degrees C would be 32 degrees F, and 50 degrees F would be 10
degrees C. But how do we express this in C++?

The reason why I ask this question is to bring two important concepts:
first, C++ offers a vast number of operators that can help us to
calculations and so forth, a second, it is a best practice to write our
objectives in something we can understand before venturing out into C++ code
world.--Source: O'Reilly Books. "Practical C++ Programming". Let us go into
these concepts in more detail.

C++ offers a vast number of operators, such as addition, subtraction and
comparison operators. Most of them comes from mathematics, such as +
(addition or plus), - (minus or dash), * (multiply) and / (divide or slash).
Also, the useful comparison operators are less-than (<), greater-than (>)
and variants of these, which are less-than or equal to (<=) and greater-than
or equal to (>=. In addition to these ones, there are anumber of "special"
ones, including ++ (increment or add by one), -- (double dash or subtract by
one) and == (double equals) - the double equals requires a section of it's
own to go over what it is. I'll go over those in sections below.

The math symbols - +, -, *, / - are used for calculations or similar
operations. For example:
int total-distance; total_distance = start_distance + added_distance;
We are working with an odometer program. The total distance would be the
distance where we've started calculating the walking distance (the start

Another example to calculate wall length from number of bricks and their
length:
int wall_length; wall_length = brick_length * number_of_bricks;
Ah, we are writing a construction calculator to calculate wall lengths
(handy for contractors). So, in the expression, we are multiplying the
number of bricks by their length to get the total length of a wall.

A more complicated one - a program that verifies if a given number is even
or not:
Int number; int dividant;
Bool is_even_number = true;
Number % dividant == 0;
Is_even_number = false;
Number % dividant == 1;
I see where you might be confused - the % (percent), or modulus operator.
When this operator is used, the program will return the remainder after a
division e.g. the remainder of 25/4 would be 1. Also, you might have seen
the Boolean operator, but I believe this is the first time you are seeing
this variable type in action.

The last example also brings an important note: the difference between "="
and "==. The "equals" by itself is the assignment operator where a value is
assigned to a variable. This one is read as "some variable is assigned to a
value." The two equals sign is simply the equivalent of saying that
something on the left IS the same as something on the right (there is a
counter operator that says something on the left IS NOT equal to something
on the right). For instance, check out the difference between the following
code:
int number = 9+1;
versus
10 == 9+1;
The first code would be read as, 'the integer variable, number, is assigned
to addition of 9 and 1." As opposed to this, the second expression would be
read as, "10 is 9 plus 1."

As opposed to these scenarios, the "counter operator' (!=, read as "not
equal to") in action (based on even/odd number verifier) would be:
Bool is_odd_number = true;
number % dividant != 0;
This is read as, "the given number is odd when the remainder of number
divided by a dividant is not zero."

I think that covers almost all operators. The reason why I left out
comparison operators is because of a topic that's coming up next: how to put
conditions so that a computer can make decisions...

### C++: getting user input and storing it as a variable

So with the basics in variables at hand, now the question becomes, "how do
we even let users enter some values into it?" This is done with a small
change from output statement (the cout):
Ccin >> var;
Where "var" is your variable. As you might have noticed, the "cin" is
"console in", the operator (in iostream library) that allows us (the users)
to type something to a program (actually, a computer) so that the program
can work with our intput.

For example, suppose if I want my computer to tell me my name, I would first
declare a string variable called "my_name," then I would ask my computer to
ask me 9ironic, is it?) what my name is. The computer would take my name as
an input then display it back to me on the screen. Here's how it would look
like:
string my_name; // My name variable.
Ccout << "Hi, what is your name?" << endl;
Ccin >> my_name;
Ccout << "My name is " << my_name <, "." << endl;
As you have seen, we can indeed embed, or put in a variable as part of an
output statement. For example:
Computer: Hi, what is your name?
Me: types "Joseph".
Computer: My name is Joseph.
And that's what it would look like when we do run a program after compiling
it (compilers and how it works will be studied further much later). The
problem becomes when we want to store a line of text; fortunately, there is
a way of doing it via getline function (a function, in this sense is a mini
program that does whatever inside it to perform a task). Here's how it
looks:
Getline(cin, string_variable);
This essentially means that we want to get an entire line of text until we
press ENTER key (return, or new line). You'll meet more syntax like this
when we get into all sorts of discussion on functions later.

More to come later...

## Saturday, July 17, 2010

### C++: Some disclaimer and legal info before continuing...

I thought I should tell you where I'm basing my notes and words from before
I continue with variables - well, if you know what I mean - for legal
reasons.

The majority of notes and words are based on a book called "C++: A Dialog"
by Steve Heller, which can be found here:
This is a free online book which introduces C++ from beginner's perspective
who might have not heard of what C++ is. I found this book very useful when
learning basics in C++.

The other book I use is "Practical C++ Programming" from O'Reilly books (I
forgot the URL for it, sorry), which is readily available. This one tackles
C++ from practical perspective, with useful commentaries on theories and
easy to understand explanations of tech terms used in programming world.

In addition, I use personal notes compiled during programming lectures at UC
Riverside, as well as general lecture notes for some examples, as well as my
own examples that I've worked on by myself or as part of lab assignment or
other things (because of a policy over there at UCR, I'll not post huge
amount of code from those exercises).

With that out of the way, let's continue with our discussion of C++...

### C++: Variable basics: declaration and assignment

So, let's talk about how to even declare data or variables and how to assign
some value to it.

To declare a variable, we need three information: the type of the variable,
the actual name of the variable and what values will it assign to. First,
declare the type of a variable e.g. int, char, etc., followed by the name of
the variable. For instance, if we are to create an age difference calculator
program (perhaps to find out who is older), we would say;
int user_age;
Here, we have declared an integer variable called "user_age," which
(hopefully) would be useful for storing our age (in my case, I'm twenty).
After this, we can use a number of ways to assign this variable to a value:
using the next statement and writing the assignment statement, or using the
"assignment operator" (=) to write our assignment. Note that this assignment
operator is way different from the way we use equals for other tasks and is
example:
int my_age = 20;
and
int my_age; my_age = 20;
are both valid. In both scenarios, the code is read as, "20 is assigned to
my-age" or "my_age is assigned 20." Also, you can do this:
int my_age (20);
which is also valid (especially in this case).

The other variable types follow almost the same format as the integer
example above. For our string variable (you need to include the string
library), we could use:
Sstring s = "whatever";
Or
Sstring s1; s1 = "whatever";
And both of them are perfectly fine. Note that when you do assign a string
to the string variable, be sure to enclose the actual string it within
quotes.

Few more examples:
Suppose if we want to declare a decimal value for calculating a car's
mileage. We can write:
Ffloat mpg;
or
double mpg;
Of these two values, the "double" type would have greater accuracy.

Now suppose if you are asked to write a voter registration program which
asks user if they are above eighteen or not. We can say:
Bool above_age;
Now we have created a Boolean variable which tests if the age entered by the
user is greater than 18 or not. I'll come back to this small code later when
I discuss conditional statement.

Next: useful operators...

### C++: Introducing data

By this time, I'm sure you know the meaning behind the sample Hello world
program - how to declare start and end of a program, how to display
something to the user and so forth. Let's now take a look at one of the
fundamental things about programming: declaring and working with variables,
or data.

Data is things that the program use to process information, such as our
names, age and even a group of car models. C++ and other programming
languages offer a vast number of built-in data types and many of these
programming languages (called object-oriented languages) offers a way for us
to create our own custom data types to suit our needs. In C++, there are
five fundamental, or built-in data types: integers, floating point numbers,
characters, Boolean (true/false) statements and pointers (addresses of
data).

An integer is a whole number e.g. 0, 20, -10, etc. A floating point number
is the technical name for decimal numbers e.g. 0.5, 2.7, -1.003, etc. A
character is, as the name suggests, used to store one letter or symbole at a
time. A Boolean statement from Charles Boole (inventor of Boolean Algebra)
stores true or false statements. A pointer is the address of a data item on
physical memory and it requires special discussion on it separate from other
data types. In addition to these four or five data types, there are a number
of variations of these, including "short" - used to store short integers
from -32,768 to 32,767 (or 16-bit numbers), double (called double precision
floating point because it is better at storing 64-bit decimal numbers and
have greater accuracy) and string (a group of characters). For our
discussion right now, let us focus on the above four - integers (or just
called int), characters (or char), bool and float/double, with an example of
how to declare such variables in the next installment.

Note: Data is the plural of "datum." Also, for better accuracy, people tend
to use double when using decimals. Pointers are useful when we work with
memory addresses and is not really useful now - it becomes relevant as we
get into designing our own data types. The "string" variable requires the
presence of "string" library.