Wednesday, December 25, 2013

C++ Tutorial #8: More Fun with Numbers

As the title says.  Now we're gonna get into more theoretical math stuff.

The Average Computer’s Definition of “Integer”
  • A whole number (no fractions, decimals, or other nonsense)
  • Can be negative, positive, or 0
  • In math, integers include all real numbers that follow the above two rules.  However, numbers are infinite, so you can't program every single existing number into a computer's system.  There has to be a limit.  Your average modern computer can recognize integers from -2,147,483,648 through positive 2,147,483,647.  (Your programs probably won't be working with anything larger than that.  If you plan to, you'll need a more advanced, higher-processing machine, and you're probably getting a bit ahead of yourself.)
Any number that does not adhere to the criteria and stay within the range will cause the computer to go completely insane. (Okay, you can get around this by using a data type other than the integer, but we'll save those for later.)

Something You Need to Know About Numbers vs. Text
One of the reasons we swear at our devices so much when they don't work is that we often overestimate their abilities.  Computers are really just big calculators, and they have their limits, one of which is that they really only know how to deal with numbers.  At its core, a computer has no idea what letters or other special characters are.

Wait a minute...if computers don't recognize non-numeric characters, how are they able use variables like string to read text?

This is where ASCII comes in.  ASCII (which is pronounced "ass-key"—I'm serious) stands for American Standard Code for Information Interchange.  It's a code that assigns every character a number.  Characters that stand for single-digit numbers have the same value as the number they stand for.  For example, the text character "5", which stands for the number 5, is assigned an ASCII value of 5.  Non-numeric characters have numeric values as well.  Uppercase "A" has an ASCII value of 65, a front slash "/" is 47, and a space " " is 32.

So, when you add text characters like "A", "/", "5", or a space, the computer doesn't read them as text they way we do.  Instead, it's told, "Okay, these are text characters with values of 65, 47, 5, and 32.  Go look at the ASCII chart to see what those are and work from there."  We programmers type characters into our source code, but we specify them as characters so that the computer knows to look up their ASCII values.  Again, the computer speaks a much different language than we do, and ASCII is what allows us to communicate with it in terms that are familiar to us.

Here's a link to a printable ASCII chart.  It might be a good idea to keep it handy for reference:

Yeah, I know there's a lot to it.  There are actually many different numeric/character codes that computers use, and a few are listed here.  ASCII values are listed in the very first column (the Dec column).  The one highlighted in red (Char) refers to the character equivalents of ASCII codes.  The other two columns (Hx and Oct) are numeric systems that I'll discuss later.

A Different Character Code

Something important to note about ASCII is that it's the American Standard Code.  In other words, it's only used on North American computers.  There are other character codes, and while they all work the same way, they might not include characters seen in the English language and might include other characters (such as the umlaut: ë, ü, etc).  A different international code, Unicode, is also used, but being an American I'm only familiar with ASCII, so that's what I'm going to work with.  If you're from another country but you use a keyboard that supports English characters, you should be able to follow along with it.  If not, however, don't worry.  It's the concept of computers and character codes that's important.

A Lesson in Numbers and Numeric Code

There are different systems of numbers that can be used when working with computers.  Humankind runs on the decimal system, which uses 10 as the basic number from which we work (which is why it's often called the "Base-10" system).  Really, all numeric systems are the same, but you're obviously initially going to be comfortable only with the one you were raised with.  Thus, we'll revisit that one before going into some of the more unfamiliar ones.

"Decimal" (Dec): The "human" number system
The most familiar set of numbers are those that follow the Base-10 decimal system.  As you probably have learned in math, human beings read and manipulate numbers through the Base-10 system.  This means that our numeric system has a total of 10 digits—0 through 9—that can be used in various combinations to create numbers.  It makes sense that man would gravitate towards a system with 10 digits—all you have to do is hold up your hands to find out why 10 is the optimal counting number for our species!  : )

Binary (Bin): Base-2
Binary is a numeric system just like the decimal system, but instead of Base-10 it's Base-2.  (Get it?  "Bi-" = 2?)  Base-10 has 10 digits to work with, but Base-2 only has 2 digits.  If you've ever seen binary code, you know those digits are 0 and 1.  So, while decimal numbers are formed by various combinations of the digits 0-9, binary numbers can only be formed from combinations of 0 and 1 (which is why you often see really long binary numbers).

Octal (Oct): Base-8
Of all the numeric systems, octal is used the least.  However, you might as well become familiar with the name in case it ever comes up.  As the name suggests, Octal is Base-8 and uses the digits 0 through 7, which gets really confusing, because it has so many digits in common with Base-10 but not all of them.  If you were to count in octal, you'd count 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, etc.  You can actually follow octal on the ASCII chart I provided.

(Because of this habit of skipping numbers with the digits 8 or 9 in them, discrepancies between octal and decimal numbers add up quickly.  For example, the octal number 112, while it looks like a number in our good old familiar Base-10 system, actually means 74 in Base-10.  Like I said, confusing.)

Having said all this, octal itself is seldom used.  I explained it in-depth because the concept of counting in strange ways is very much present in the next system.

Hexadecimal (hx or hex): Base-16
Here's a weird one that is used often—not necessarily in an introductory C++ tutorial, but in more advanced programming.  If you're planning to go into technology as a field, get comfortable with hex.  Hexadecimal is a Base-16 numeric system, which might confuse you.  After all, the only digits that exist to mankind are 0 through 9.  If man only created 10 digits, how do we work with a numeric system that supposedly has 16?

The answer is we use letters.  Base-16 uses digits 0 through 9 the same way Base-10 does, but it adds the letters A-F on the end (so, in hex, A is a digit that stands for 10, B stands for 11, etc.).  To create numbers, it uses a combination of 0-9 and A-F.  What's really weird about Base-16 is that, since it includes all Base-10 numbers, hex and decimal numbers can look very similar.  In fact, the digits 0-9 represent the same numbers in both hex and decimal (so 0 in decimal is 0 in hex, and 9 in decimal is 9 in hex).

After 9, however, things get strange.

Base-10 (decimal):        Base-16 (hex):
10                                  A
11                                  B
12                                  C
13                                  D
14                                  E
15                                  F
16                                  10
17                                  11

And the list goes on.  As you can see, in hex, you go from 0 to 9, then A to F, and then repeat the process, but this time with a 1 in front.  So what we know as the number 16 is actually 10 in hex.  Hex numbers continue from 10 to 19, then 1A to 1F, then 20 to 29, then 2A to 2F, and so forth.  This relationship with the Base-10 system is also shown in the ASCII chart I provided.

Again, the only system you need to be familiar with in introductory programming is the decimal system.  Everything you need to know about Base-2 you already know—it's used in machine code, the only language a computer understands, blah blah blah.  I'm just telling you about these other systems because, seeing your interest in the inner workings of a computer, you're probably going to become far more involved in tech, and someday you'll be working with other numeric systems very closely.  Not in this tutorial, but someday.

Here's Something That's Relevant Right Now: Other Numeric Variable Data Types

Back to the C++ realm.  You're already familiar with the data type integer, but there are many others.  All groups have their benefits and drawbacks, so it's up to you to decide when and where you want to use them.

One last important thing to note: because computers are limited calculators, different data types can only be accurate for so many digits or decimal places.  Afterwards, they may not calculate correctly.  For example, the integer is accurate to 7 digits.  So if you make a calculation that has a 7-digit answer, such as 5,294,863, the computer will store the number 5,294,863 and work with it without making any errors.  However, if your number has more digits (5,294,863,700), after the 7th digit it will either round off the number, cutting it back down to 7 digits, or begin spitting out random numbers after the 7th place (so you could end up with something like 5,294,863,920).  You probably won't be working with very big numbers in the beginning of your programming career, but if you do, keep in mind how accurate you want your calculations to be when choosing data types as some are more accurate than others.

The integer (int) is a whole number, negative or positive.  The benefits of using integers are that they take up little memory (4 bytes per value), have decent accuracy (up to 7 digits), and have a pretty good range that the computer can handle (-2,147,483,648 through positive 2,147,483,647).  However, if you're looking for something with better accuracy or range, you'll need to use something else.

The short integer (short) is an integer that takes up 2 bytes and has a range of -32,768 through 32,767.  If your computer is low on memory, use this one instead of the regular int.

The unsigned integer (unsigned) takes up 4 bytes but has a greater positive range than the regular int.  Basically, it means the unsigned nixes the negative numbers to increase range of positive numbers from 0 through 4,294,967,295 without taking up any more memory space than the regular int.

The float (float) takes up 4 bytes and allows you to use decimals.  It can be used to represent any number between -3.4 * 10^38 (-3.4 times 10 to the 38th power—a really small number!) and 3.4 * 10^38 (a number of equal proportions in the opposite direction!).  It's accurate to 7 digits, including decimals of course.

The double (double) is like float, except it takes up 8 bytes and can represent any number between *takes deep breath*: -1.7 * 10^308 and 1.7 * 10^308.  It's also accurate up to 15 digits.  Holy cow.

All right.  I think we've talked enough about numbers.  Print out that ASCII chart and jot down some notes on the different data types.  You don't need to memorize everything now (you'll begin to remember these guys automatically as you use them in programs).  It's a good idea to get used to the idea of using as little memory as possible in a program while still retaining decent accuracy and having a data type sufficient for handling the numbers and values you'll be using in your programs.  Granted, a lot of modern computers have enough memory to handle whatever kind of data type you throw at it.  But it adds up, and if you end up using a lot of memory unnecessarily you could slow down your program, especially if you're trying to run it on an already slow or low-memory system.

Conservation vs. usability.  Always a balancing act, made even more entertaining with math.

Thursday, October 17, 2013

C++ Tutorial #7: Doing Math With Variables

This is going to focus on a different variable from what you worked with last time: int, which stands for integer (which, if you block out memories of math class, is a whole real number that can be either positive or negative).

The Operator(s)

(Insert obligatory Marble Hornets reference)

Now, when you do math with variables, you'll have some operators to work with.  Operators are symbols like + and - that stand for various math operations.  You don't always write them in code as you would on a piece of paper, since the keyboard doesn't have all the typical symbols (there's no key for the standard "divide by" symbol you see in math books).  So here's a guide for using basic operators in programming:

+   Means "add", and looks the same as its standard symbol.
-    Means "subtract" and also looks the same as it does in math books.
*    Means "multiply".  It's the asterisk, not the x-key.
/    Means "divide".  It's a forward slash.
=   Means "equals".  You've noticed that it's generally used for declaring variables.  You can substitute the word "equals" for "is".  "This variable is five."  "This variable equals five."

There are more operators, but we don't need to discuss them right now.  These are the main ones you'll be using.

Outputting Variables in Programs

Say you do your math in a program and want to share your findings with any user who runs your creation.  You'll need to output it somehow, and thankfully there are not one, but two ways to incorporate the values of variables into your cout statements.

Let's say I have these lines:

int first = 5;
int second = 10;

You know that if you add those two, you'll get 15.  However, your user will not because the user probably won't be snooping through the code of your programs.  Therefore, you need to tell them using a cout statement.  And so enter our two methods:

Method #1: the third variable

One thing you can do is create a third variable whose value is the result of the math problem, and then insert that third variable into the cout statement.  So, the snippet of code would look like this:

int first = 5;
int second = 10;
int third = first + second;  //creating the third variable

cout << "The value of first + second = " << third << "." << endl;

The output would look like this:

The value of first + second = 15.

See how that works?  The computer knows to read third and look for the number that third stands for.

Method #2: inserting the problem into the cout statement

In most cases, the third variable method is helpful, but sometimes (and especially with smaller practice programs like this one) it's easier to just place the math problem directly into the cout statement, like so:

int first = 5;
int second = 10;

cout << "The value of first + second = << first + second << endl;

Looks slightly different, and there's no third variable, but the output is still the same because the computer takes the value of first, the value of second, adds them, and displays the resulting value.

The value of first + second = 15.

You end up in the same spot; it's just that in certain situations it might be easier to use one method than the other.  Be sure to practice both.

Practice Programs: Integer Variables

I'm not going to go over the other numeric variables at this point.  Right now, I just want you to understand how to work with the most basic numeric variable.  Thankfully, it's really easy to come up with practice programs for int variables, so once you see a couple of models here you should be able to practice them on your own quite easily.


In this program, the program already has the values of the width and the height of the rectangle.  It's pre-programmed in, so we don't need to ask the user for any information.  We take this pre-programmed information and perform a couple of calculations with it.  We then store the result of these calculations into two variables, area and perimeter, and when we want to output the information, we just put the variable names into the cout statements (as we did in the first outputting method with the third variable).

#include <iostream>

using namespace std;

int main()

     //these variables are already programmed in.
     int width = 5;
     int height = 8;
     int area = width * height;
     int perimeter = (2 * width) + (2 * height);

     cout << "The width of the rectangle is " << width << endl;
     cout << "The height of the rectangle is " << height << endl;
     cout << "The area of the rectangle is " << area << endl;
     cout << "The perimeter of the rectangle is " << perimeter << endl;

     return 0;


Type this out, save it in your programming folder as "Rectangle.cpp", compile it, and run it in Command Prompt.  The output should look like this:

The width of the rectangle is 5
The height of the rectangle is 8
The area of the rectangle is 40
The perimeter of the rectangle is 26


In this program, we'll ask the user to input their age and their grandmother's age, and we'll calculate the difference.  However, instead of putting the difference into its own variable, we'll put the math equation in the cout statement and output it directly from there.

#include <iostream>

using namespace std;

int main()
     int myage;
     int grandma;

     //get the user's age
     cout << "How old are you?";
     cin >> myage;
     cout << endl;

     //get the user's grandma's age
     cout << "How old is your grandma?";
     cin >> grandma;
     cout << endl;

     //Find the difference by putting the equation in the statement.
     cout << "The difference between your ages is " << grandma - myage
          << " years." << endl;

     return 0;


Note that the final cout statement is really long, so I had to break it up.  In a cout, every piece consists of the two less-than signs and some kind of component (either the statement in quotation marks, a variable name or an endl).  You can break up those little pieces if you have to (compilers generally don't like long lines in code), just make sure the piece is complete (so you have the << and the component), and be sure to indent so that it looks neat.  For example:

cout << blah blah blah really long line
     << start next part here, with signs lined up nicely

Now, back to our Granny code: this is what the output looks like.

How old are you?  18
How old is your grandma?  83
The difference between your ages is 65 years.

That's quite enough for now.  Next time we'll talk more about char and string variables.

Sunday, October 13, 2013

C++ Tutorial #6: Input and Output (I/O)

***Note: In computer science, input and output is almost always abbreviated as "I/O".***

The Basics of the Input/Output System

This may bring back memories of math class.   The concept of I/O is simple: you enter something for the input, and you receive something back—the output.  You place your change into the vending machine and get a snack or drink.  You punch equations into a calculator and you receive answers.  You enter your password and gain access to your online account.  Computers are quite good at I/O, the simplest form being taking what the user enters and spitting it back out.  You type a-whoop-a-dee-doo, and the program reads it and repeats a-whoop-a-dee-doo, either by itself or in special context. That’s what this section is about.

Here's Another Program For You to Stare At

Source code for the very polite and proper “Introductions.cpp”.  It's also the first full program in this tutorial with comments!

#include <iostream>
#include <string>   //notice the second "#include"
using namespace std;  //Remember, this line's important too!

int main() 

string name;

cout << "What's your name?  " << endl;   
//I added a couple of spaces on the end, just for formatting.
cin >> name;   //OH CRAP THAT'S NEW
cout << endl;  //equivalent of hitting "Enter"
cout << "It's very nice to meet you, " << name << "." << endl;

return 0;

So let’s break that down…

  • #include <iostream>: "Include text from the file iostream, which tells the compiler what cout and cin mean."
  • #include <string>: "Include text from the file string, which tells the compiler what a string variable is."
  • using namespace std: Sometimes (like when I tested the code just now) I forget this line.  If your program errs, double-check to make sure this guy is in place.
  • int main(): “Begin the main function."
  • { and }: "This is where the main function begins and ends."
  • string name: (This is a variable declaration.)  "There is a variable in this function.   It is a string [text with multiple characters] variable, and we’ll call it 'name'."  The variable is the input, or whatever the user enters (this program is interactive with the user).
  • cout << "What is your name?  " << endl;: "Display 'What is your name?' with two extra spaces on the screen."
  • cin >> name; "Read what the user types on his or her keyboard.  Whatever they type before pressing Enter will become the value of the variable name (that's what name will mean)."
  • cout "It's very nice to meet you, " << name << "." << endl; "Display on the screen: 'It's very nice to meet you, ' then the value of the variable name, and then '.'"  This includes a space between "you," and the name that the user entered, as well a period at the end.

And you know what the rest means.  If all goes well, this is how the program should work (with the program output in green and my user input—what I type—in orange).

What is your name?  LadyPakenham
It's very nice to meet you, LadyPakenham.

The input (your name) is known in the program as the variable (or name).   The value of name is static, so whatever the user types in becomes name.  Then it’s placed wherever it is told to be placed.  Also, notice how cin (which, being the opposite of cout, is responsible for recording input rather than displaying output) will store whatever you type until you hit Enter.  With the exception of special characters, it'll store whatever you want.

In other words, you could type anything, which really opens the door for immaturity.

What is your name?  Fartface McFecalpants
It's very nice to meet you, Fartface McFecalpants.

The possibilities are endless.

A Couple Things to Note About cin

You knew this would be a problem: cout and cin are close to each other, but have their differences.  A big one to remember is that their signs are different:

cout << name;   //cout uses less-than signs
cin >> name;    //cin uses greater-than signs

I try to remember it this way: both signs kind of look like mouths talking.  cout kind of looks like he's doing all the talking, while cin looks like he's listening to the stuff in front of him talking.  Get it?  Output is like talking, recording input is like listening to somebody else talk.

There's something else to remember, too: unlike its companion, cin has a bit of a quirk to it.  Notice how, when using cout, you include an endl on every line (which, again, is like the program pressing the Enter key on a keyboard when displaying something onscreen).  You probably are going to want to have a line break and carriage return inserted after the user types a response, too (otherwise, that'd be one long line of input and output).  However, cin doesn't like it when you insert an endl on the same line as it.  So to say this in a program:

cin >> name << endl;

would be illegal.  It also looks kind of weird.  After all, cin records input, but it's cout's job to display things on screen like a line break/carriage return.  So, you have to output the endl on a second line and as a second statement, like this:

cout << name;
cout << endl;   //Don't forget: both statements end with semicolons!

Here's Another Program With Lots of Variables

You might be okay with typing Fartface McFecalpants and storing all that in one variable.  But in some cases, you don't need to.  The program will so kindly allow you to differentiate your first name from your last name.  Besides, who ever said you could only have one variable?

Source code For "NameGame.cpp":

#include <iostream> //tells compiler what cout and cin are
#include <string>   //tells compiler what string variables are

using namespace std;

int main()
string first;       //three variables,
string last;        // all pertaining to names.
string middle;

//Find the user's first name
cout << "What is your first name?  " << endl;
cin >> first;   //records what the user types
cout << endl;
//Find the user's last name
cout << "What is your last name?  " << endl;  
cin >> last;
cout << endl;

//Find the user's middle name
cout << "And your middle name?  " << endl;
cin >> middle;
cout << endl;
//Put it all together aaaand...
cout << "So your name is " << first << " " << middle << " " << last << "?"
     << endl;  //Had to break up a line there...
cout << "That's a funny name.  But it's not your fault." << endl;

return 0;

You see a lot of familiar faces here, but you’ll notice that I have three variables instead of one.  I assign each a name as they are entered—first, last, and middle.   Then, when it comes time to spit them back out, I put in variable in the order I want them to appear (again, including spaces for formatting).

So let's get back to our good ol' friend Fartface:
What is your first name?  Fartface
What is your last name?  McFecalpants
What is your middle name?  Philip
So your name is Fartface Philip McFecalpants?
That's a funny name.  But it's not your fault.

Indeed.  Note that if, in the source code, I had ordered the variables last, first, then middle, the output would have be McFecalpants Fartface Philip.  Which is just weird, right?

So, until next time, have fun writing programs where you can enter in whatever the hell you want.  And remember: you don't have to just write carbon copies of the examples I post!  When I was learning C++, I tried to think up of my own programs that used the same concepts but did different things.  It's a great way to really get familiar with the language, and practice is so important to becoming proficient in anything you do.  And remember that there's no limit to how many variables you can have, so have fun with them!  : )

Saturday, October 12, 2013

C++ Tutorial #5.5: Variables

Okay.  I want you to take a deep breath.  We're going to venture ever-so-slightly into the math arena.  No, not calculus.  But I do want to talk about variables, because they're the one component about the C++ language that I didn't get to in my last post.

Before learning any kind of programming, you should have a good basic theoretical knowledge of how algebra works.  A variable is any factor of piece of information that can change or have multiple values.  For example:

x + 3 = 7

Before doing any math, just think about the problem.  What do we know right off the bat?  We know that 3 = 3, and 7 = 7.  These numbers, whose value we can see and understand at first glance, are called constants.  We have faith that 3 will always equal 3, and 7 will always equal 7.

However, x is another story.  In this problem, x is the variable.  Okay, maybe you were able to figure out pretty easily that 4 + 3 = 7 and therefore x = 4.  However, x = 4 in this equation ONLY.  Look what happens when I put it in another equation:

x -12 = 1

In this case, x = 13.  Whenever you have an equation with a constant, the value of the constant will not change.  So if I were to present the problems 4 + 3 and 17 - 3, the value of 3 stays the same.  3 is always 3.  However, in the above two examples, x was given a different value in each problem.  The value of a variable can change depending on the problem.

So what does this have to do with programming?  Well, C++ uses variables too, though not always in the same way.  In math, variables are always numbers.  However, in C++, there are many types of variables for many types of information.  Here's a list of the one's we'll be using most often:

Int: an integer, or whole real number that is positive or negative.
Char: a character, such as B, 7, or $.
String: a bunch of characters together, such as "button" or "I love to swim".

Computers store all kinds of information—names, dates, passwords, confirmation numbers, etc.  These are just a few of the several types of variables that are required to store all this information.  We'll discuss the other types once you're comfortable with the programming/compiling process in general.

Declaring Variables

The syntax of declaring variables is actually quite simple:

type name = value;
int age = 20;
char grade = A;

You can assign a value to a variable immediately, or save it for later.

int age;
//other code blah blah blah
age = 20;

You can also do math in programming.  However, the nice thing about that is that you don't actually have to solve the problems.  You just have to write them out and make the computer solve them for you, like so:

int first = 12;
int second = 5;
int third = first + second;

The computer will read that third line, check the values of first and second (12 and 5 respectively), add them, and then store the resulting value (17) in the variable third.  Then, you can do more computations with the variable third, and in the future the computer will always read third as having a value of 17.

This is a short post, but I'm going to stop here.  The reason is that, while it's nice to be able to make your programs do your math for you, what good is it if the final product can't be displayed on your screen?  In Tutorial #6, we'll talk more about cout, its good buddy cin, and what roles they play in making a program interact with a user.

Thursday, October 10, 2013

C++ Tutorial #5: More Grammar Rules/ERRORS!

Now that you've seen your first C++ program, you're starting to get a feel for what this language looks like.  Again, it's just like any other language—English, Spanish, Russian, Japanese, etc.  All languages have a few things in common: they have rules on spelling, grammar, mechanics (like punctuation), and overall structure (or syntax).


The main component of any language, including C++, is the vocabulary.  A language is built with words, some being more important than others.  The really important words in C++ are called keywords.  Here's a list of some of them: 

Words that were left over from the older C language (but are still used in C++): 
auto         double     int             struct
break       else        long           switch
case         enum      register     typedef
char         extern     return       union
const        float       short         unsigned
continue   for         signed        void
default     goto       sizeof         volatile
do             if            static        while

Words that are specific to C++:
asm                false             private                  throw
bool               friend            protected              true
catch              inline            public                    try
class               mutable       reinterpret_cast   typeid
const_cast      namespace  static_cast            using
delete             new             template               virtual
dynamic_cast operator       this

(Sorry. I tried to line those up the best I could, but Blogger was not on my side.)

Now, do you need to memorize all these right away? No. In fact, in my programming experience, most I haven't even used. You'll begin to learn them and the context in which they're used as time goes on.

Having said that, I do recommend you print this list for future reference. The reason? All of these words are reserved words, meaning they can only be used for their intended purpose (for example, int can only be used to declare something as an integer number). Reserved words can't be used for naming functions or variables (which will be discussed somewhere in the next couple of posts), so keep that in mind when naming stuff in the future.

Questions or Comments?

Comments are essentially digital Post-It-Notes you put in your programs. You can insert them at any point and in as many places as you want in your source code files. The idea of using code Post-It-Notes to remind yourself of what you’re doing may sound silly to you if you’ve only programmed very small files like the one I used as an example in the last post. However, if you’re writing an operating system, which can take months if not years to complete and debug, you need little reminders in your code to help you out. However, how do you insert such reminders without the compiler thinking it’s some crazy part of the code?

// Like this.
// Two front slashes for each comment.

// Anything in front of the two slashes is ignored
// by the compiler.  However, each line of comment
// ends when the line ends, so you have to type
// another two slashes if you want another line.
// You can group many lines of comments together.
// Comments or not, compilers don't like long lines of code.

You can use comments to disable parts of your code that you don’t want/aren’t working but would be inconvenient to remove.  However, be sure that you don't comment out anything important, and if you want to bring back some commented code into a program, you have to "un-comment" it (removing both slashes from the line, which in turn "un-comments" the whole line).

All Major Components of the C++ Language Explained Briefly

Keywords are like words, which must be used in context.
Operators and other symbols are used for numerical operations or act as punctuation (+, <<, ;)
Parentheses, or parens, group certain instructions for the words. You'll do more work with parentheses later.
Statements are what all these words and instructions are together, ending with a semicolon.
cout << "Hello world!" << endl;
int age = 18;
Curly braces group parts of a program, usually functions. { }
Comments don't add anything to the program itself and are ignored by the compiler, but are important because they are notes and reminders for the programmer and anyone else reading the code.
Everything together is the language’s syntax (how a language is put together).

The Most Commonly-Forgotten Rules of the C++ Language

1) Braces come in pairs.
2) All statements end in a semicolon.
3) Spaces and indentation are optional in the text editor (like Dev-C++), but not in command lines.
4) A main() function is required. That’s the shortest a C++ program can be.
5) C++ is written mostly in lowercase, and it is case-sensitive.

What Happens if You Break the Rules: ERRORS

I've heard some programmers joke that the process should be called debugging instead of programming because it’s just about guaranteed that your program will have some problem with it, no matter how little code there is.  With the exception of seeing it while you’re writing the source code, the earliest you might catch a mistake is when you go to compile it and something goes wrong.  You might also catch an error later, as creating a finished product involves many steps. There are four main types of errors:

Compiler Errors: These are considered the “easy errors.”  When you go to compile the program, an error in code makes it so that compiling cannot take place.  The final product (the .exe file) is not made, and you are informed exactly where the error is and what general problem it is (for example: program.cpp: in function ‘main’: program.cpp:6 parse error before “return”)

In this case, you are told what program erred (as if you didn’t already know), in what function it occurred, in what line of code it occurred, and what type of error it was and where exactly it was. (In this case, I had written a cout statement but forgot to put a semicolon at the end. Oops!)

Linker Errors: These usually have to deal with misspelled commands or a problem with linking many source code files (if your program is that complex). The compiler doesn’t care (all it does is translate), but the linker can’t put the pieces of the program together if there are misspelled commands—after all, how’s it supposed to know what that piece is supposed to do?  These errors are more difficult to figure out because the error messages are quite vague, usually talking about an “undefined reference to [misspelled word]”.  No line number is given.  That means you just have to look for the misspelled word outlined in the error message.  Grr.

Run-Time Errors: The compiler and linker are both happy, and the file is made.  However, for some reason when you go to run it, it shuts down immediately or unexpectedly partway through the program’s course.  These errors aren’t the easiest to spot but they’re not the hardest, since you can tell at what point in the program’s course the error occurs.

Bugs: These are the worst. Not only are the compiler and linker happy, but the program can still run just fine.  The program is still a program and there’s nothing technically wrong with the code.  The problem?  It doesn’t do exactly what you wanted it to do.  Maybe it does some math wrong, or it doesn't display with the neat pretty formatting you wanted.  This type of error requires intense vigilance and critical thinking to be found.

Lastly, two types of error messages:

Warnings: the file is still created but there’s something about it that the compiler and/or linker doesn’t like. It means that they found something that, in context, looks unusual or suspicious. It might be a bug, or it might be them being touchy. But the program will still run—just, in the case of a bug, perhaps not exactly how you wanted it to.

Critical (or fatal) errors: at this point the compiler and/or linker refuses to finish the job. This means there is a true error in coding and not just something that looks suspicious, and you need to fix it before the final product can be created.

And there's your grammar lesson for the day.  Really pour over this post and become familiar with its contents, because this is the kind of stuff you'll be dealing with when you're modifying and debugging your programs.

Friday, October 4, 2013

C++ Tutorial #4: Your First C++ Program

Okay—this is where things are going to start getting a little confusing.  Really, the only way to learn the basics of a C++ program is to have one thrown right at you.  You won't understand a thing at first, but you'll learn as you dissect it.  And it will be a simple program, don't worry!

Tip: when you go to save the programs you write, BE SURE to save them in your designated programming folder.  In addition, now would be a good time to open up Command Prompt and use cd.. and cd to navigate to your programming folder.

Programming Project #1: Hello.cpp

Ready to write your first C++ program?  Good!  Let's go!

1) Open Dev-C++.
2) In the toolbar, click File > New > Source File.  (If you like keystrokes, you can also use Ctrl-N.)
3) Type out the following code exactly.  Any typo will result in an error when you go to compile it into machine code.

Note (this is not part of the code): in "int main()", those are two regular parentheses, with square brackets enclosing the other part of the program (the "cout" part and "return 0").  And for all indentations, I use a single tab, but it doesn't matter.  Just indent somehow (it looks neater).

#include <iostream>

using namespace std;

int main()
     cout << "Hello, world!" << endl;
     return 0;

4) In the toolbar, click Execute > Compile (keystroke: Ctrl-F9).  A "Save" box will pop up.  Make sure you're in your programming folder before you save.  Name your program Hello.cpp and hit Save.  It will then begin compiling.
     4a: If everything goes well, it'll compile nicely and say Done when it's done.
     4b: If something goes wrong, it'll give you an error message with the line number where a problem was found.  Go back and make sure you typed out everything correctly (C++ is a very finicky language).  Check other lines in addition to the line reported in the error.  Sometimes the error in one line is caused by a mistake in a completely different line (you can imagine how frustrating this gets in larger programs).

5) In the same folder where you saved Hello.cpp, you'll see another file called Hello.exe.  Remember how we talked about having two files for every program you write?  Hello.cpp is your source file (your original code in C++).  Hello.exe is the executable file, which is written in binary and can be understood by the computer.

6) At this point, you've created a fine, working program.  But there's one small issue: if you were to run Hello.exe, you'd see a black box appear for a split-second and then disappear.  This is because your computer runs fast, and all the program commanded it to do was flash "Hello, world!" on the screen for a split-second.  In order to get a good look at your work, you have to take a few extra steps:

6a) Open Command Prompt by searching for it or running "cmd.exe". 

6b) Navigate to the folder where you're keeping your programs by using cd.. and cd.

6c) Once you get to your designated folder, type "Hello.exe" and press Enter.

Your program will run and close, but since you were already in Command Prompt anyway when you ran it, the window won't close when the program stops.  This way, you'll have validation that the program worked exactly as intended.

Dissecting Hello.cpp
  • Why are there so many semicolons?  C++ is a language.  Therefore, it should be thought of as a language, no different from any other language.  Like other languages (for example, English), C++ has rules regarding its syntax (how the language is structured).  There's grammar, punctuation, and good structure vs. bad and difficult-to-understand structure.  Each line of code should be thought of as a sentence.  The semicolon (;) acts as a period for most "sentences".  The tricky thing is remembering where they go and where they don't.  That's something you'll get used to over time.  Generally, major lines such as #includes or starting functions (see below) don't have them, while more specific lines such as declaring variables and giving minor commands do.
  • #include <iostream>—this is something called the preprocessor.  There's a lot of code that needs to go into programs to make even small commands work—extra code that no programmer wants to have to write every single time he or she creates a new file.  When you downloaded Dev-C++, you also got a bunch of extra files with code that's commonly seen in programs.  These are called library files.  One of the most common library files is iostream.  Thus, #include <iostream> tells the computer, "Take the code from iostream and just stick it right here."  Really, all it does is copy-and-paste from another file, saving you time and aggravation.
  • using namespace std;—that's standard.  Namespaces are kind of complicated, and—to be perfectly honest—the introductory class I took really didn't go too far into them.  As I say in my "obligatory disclaimer" (see the tabs at the top of the page), I will not elaborate on any subject with which I am not appropriately familiar.  For now, just know that it's a line you have to include in all your programs in this tutorial, always after #include <iostream>.
  • int main()—programs in C++ are divided into functions.  A function is a chunk of code that does something; each function in a program has a different job or purpose.  Every program in C++ has at least one function.  In the beginning, you'll be writing one-function programs, and your single function will be entitled main.  Later, when you're writing programs with multiple functions, main will still be in charge of other functions.  The contents of functions must be enclosed in curly braces.  The int part will be discussed later.
  • cout—pronounced "see-out".  This basically means "output this on the screen".  You use two less-than signs (<<), type what you want to be displayed with quotation marks (the quotation marks won't be displayed), and then add two more less-than signs.
  • endl;—also referred to as an "endline".  This means "insert a line break and carriage return".  It's the C++ equivalent of hitting the Enter key after displaying "Hello world!"
  • return 0;—here's where int comes back.  Computers are really just big calculators, and they deal in numbers.  Therefore, all functions must end by reporting back some kind of number value to the program (which, in turn, reports a number back to the operating system before closing).  By declaring the main function as int main, we stated that the number to be returned would be an int, or integer.  Different numbers that are returned mean different things.  Returning 0 means the program completed and is closing without any issues or errors.  Returning 1 means the program is closing, but because of some kind of problem that occurred.  Get used to writing this line, because all functions must return some value, and main almost always returns a value of 0.
At this point, the function main is done, so we close it off with a curly brace.

I'm going to look in my old notebook for more examples of programs you can try out.  For now, if you want practice, you can write more programs outputting different things in the cout statements.  (You can even write more than one cout statement, if you want!  Just make sure they're on different lines, and write them all using the same syntax.)  And, as always, comment or email me with any questions.  I'll be happy to answer the best I can.  :-)