• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Learn it Yourself: C++ Course

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Frodo Baggins

New Member
Joined
Aug 29, 2001
Location
City of Dreaming Spires
Hey, just a bit of an introduction: I tried to learn C++ over the summer. Although I did learn bit by bit, I have to say that it pales to comparaison to what I learnt in class this semester (just started a bit ago). The documents that my teacher writes out to teach us are well written and are appropriate for idiots

I did see the lack of stickeys in this section, and if some people approve of it, then perhaps they can make this a stickey.

I will be posting lessons, bit by bit. It should teach you the basics to the intermediates of C++. This is exactly what I am receiving in my classes (every day, every week), and this includes, lessons, assignments, quizes and tests

These lessons were written by the Computer Science department at Hillcrest High School in Ottawa, Ontario, Canada

This idea was right out of the blue, so if you guys like it/dislike it, then please give me a PM so I know to keep it coming

This is a Grade 12 course on computer programming. Basic to intermediate knowledge from programming was learnt last year using Quick BASIC. This course assumes you know the basic concepts

Be careful! Because of the forum's code, some things, such as indenting are not reflected in the course lessons.

 
Last edited:
Lesson 1: Introduction to C++ and Java. (DAY 1)

1.Why C++?

C++ has many advantages as a language:

- portability – It can be used to program on a PC, a MAC, or a SPARCstation.
- speed. Very fast. It executes almost as fast as machine code.
- ability – A C++ program can do almost anything a machine code program can.

From a teaching perspective, I like C++ because of the third item. There are many details like memory allocation, pointers, and OOP that are not possible with other languages.

While I am inclined to think that C++ has no disadvantages, I dutifully list some possible problems with C++:

- it is complicated. The more you want to do with C++, the better you have to understand what you are doing. Gone are the good old days of BASIC.
- it is not secure. Viruses, Trojans – these can all be programmed in C++. Ergo, C++ is not suitable for programming applets on the internet.
- it lacks good garbage collection. That is to say, variables and other objects that are created can sometimes be left sitting in the memory even after the program is done with them. This causes problems for the user that are difficult to trace.

2. Why Java?

Java also has its own advantages as a language:

- portability – Java is another cross-platform language. It is even more portable than C++.
- security – Java is like C++ with its claws clipped. This is to make it safe for the internet. Being a newer language, it is also written with safer structures in place.
- applets – Java can be used to write small programs for use on the internet, called applets. Applets are a Java invention, but we can expect many more similar internet languages to be invented in the near future.
- OOP. Java is 100% OOP, which makes it a very clean language. OOP code is easy to debug.

But again, there is another side to every coin…

- Java is slow because it is an interpreted language.
- OOP. If you don’t know what OOP is, you have to learn that before you can learn Java. C++ can be OOP or non-OOP, which gives you time to learn the ropes a little before you get into OOP. Get it? Of course, I already mentioned that many people prefer the fact that Java is pure OOP.

3. High-Level vs. Low-Level

A computer language is a nice intermediary between the computer and the human. The computer understands only numbers. The human understands only words. A programming language is a language that is close enough to English to be understood by the programmer, but then is translated into the computer’s lingo - numbers.

Machine Code – the bottom floor.

A company creating a processor (like Intel’s Pentium processor) must come up with a vocabulary list of instructions that both the human and the CPU understand. This vocabulary list is called an instruction set. An hypothetical CPU might have an instruction set like this:

Code Instruction
01 Print
02 Clear screen
03 Jump to this line

A program that gets the computer to print “hello” repeatedly, would be written in English as…

1: Clear the screen
2: Print “Hello”
3: Jump to line 2

In the computer’s language, machine code, the computer would read this as…

02
01 103 100 107 107 110
03 02

The first two digit number in each line is the code corresponding to each command. What about the extra numbers on the second line: 103 100 107 107 110. Any guess what they mean?

Note also that this example is fictional . The reality is that an instruction like “clear the screen” while it seems simple enough, actually involves several computer instructions. So this program, three lines long in English, would take perhaps a dozen lines of machine code.

Machine code is the lowest level language possible. It is the language of the computer itself.

Assembler – The next level up.

For obvious reasons, computer programmers decided to design a language that replaces numbers with words to make it easier to read. Assembler language is essentially machine code, but every instruction code has a three or four-letter word (called a mnemonic) replacing it. There is a one-to-one relationship – every numerical code has a mnemonic – making translation a snap, while making the code more readable. Back to our hypothetical example, we add a third column:

English
1: Clear the screen
2: Print “Hello:
3: Jump to line 2

Machine Code
02
01 103 100 107 107 110
03 02

Assembler
1: CLS
2: PRT HELLO
3: JMP 02

Here you can see that the mnemonic for “print” is PRT and for “clear the screen” is CLS. It is the job of the assembler to convert each instruction from its mnemonic to a numerical equivalent. (While this example makes assembler language look easy like BASIC, we should remember that in reality a process like clearing the screen or printing a word would actually take many instructions in assembler/machine code.)

In summary, machine code (and assembler) is at the lowest level of language possible. It is the fastest language possible, since it is written in the language of the CPU, but it is the most difficult to read. It is also machine specific – that is , every different model of CPU has a different instruction set. That is what makes a Mac a Mac and an IBM an IBM. Computer programmers that write in machine code would have to write a slightly different code for every different CPU type. Programming in machine code is left to the experts.

Higher Level Languages

BASIC (Beginner’s Applied Symbolic Instruction Code) is a high level language. It resembles English more or less, and resembles assembler very little. Therefore it takes quite a bit of translating. Translating Basic to machine code is a lot like translating Inuktitut to English using a dictionary. Some words translate easily, others not so easily. And the final product, though understandable is not efficient. For example:

English: Go to the hospital

Direct translation from Inuk: Move your body forward to the building with many sick people.

What is four words in BASIC could easily translate into 30 words in machine code. For this reason, BASIC is not as efficient nor as fast as other languages. But for a beginner’s language, it can’t be beat.

C++ and Java are also high level languages, but they are arguably lower level than BASIC. The lower the level of the language, the more access to the CPU and its functions.
Compilers and Interpreters

The code written by a programmer is referred to as source code. Source code is always written using a simple ASCII text editor. We could, for example, write all of our programs with Notepad or WordPerfect or any other text editor. But source code cannot be executed (run) until it is converted first to machine code.

Translating source code to machine code requires either a compiler or an interpreter. An interpreter converts a program instruction by instruction. A compiler goes over the entire program and translates it, creating a machine code version of the program, called the object code. Then the object code is executed.

Consider a human interpreter – one who translates a speech line by line (as in the news or on CSPAN).
On the other hand with a compiler the speech is completely translated first and then given to the reader.

Interpreting a speech line by line, as in the first case, will get you information sooner, but not faster. This is ideal for a television translation. Nobody wants to wait until the speech is finished before the translation kicks in. A compiler would do exactly this, translating a whole speech before sending it on to the reader. A book translation is an example of a compilation. Nobody wants to buy a book one sentence at a time (except maybe for Stephen King fans).

An interpreted language is:

- slow during execution (also called run-time). Every time the program executes, the interpreter goes over each line , translates it, then executes it.
- faster to debug. Each line is translated as it is written, so errors are spotted immediately.

BASIC is an interpreter language. As you might recall, if you make a spelling error while you write in BASIC, it is spotted immediately and you are forced to fix it. This is a great advantage to the beginning programmer.

A compiled language is:

- slow at first. The programmer has to wait while the whole source code is translated. This could take minutes. All errors are detected during compilation, and the code has to be fiddled with, compiled, fiddled with some more, compiled again, until all bugs are fixed.
- very fast afterward. Once the program has compiled properly, it does not have to be translated again. The executed code is a machine code translation, which runs very fast.

C++ is a compiled language. It does not check for mistakes until the source code is compiled. This is a disadvantage for the beginner, because the compiler will allow the programmer to write anything – you could write a poem to your pets – without any corrections. Then when the user tries to compile the code, the compiler will list all the errors it found. It is common for a beginner in C++ to labour for half an hour on a code only to have the compiler find 100 errors in it.

Finally, Java is curiously both a compiled and a interpreted language. More on this later.
 
Last edited:
Lesson 2: The C++ IDE (DAY 1)

Lets go over some basic facts.

First, to create a C++ source file (you call it “the program”) we need a text editor. We could use Notepad, for example. Next, to compile our program, we need a compiler. There are many compilers available over the internet for free. We will use one taken from the GCC (GNU Compiler Collection) because they are the best.

Now we have a text editor and a compiler. Unfortunately, for those of us raised in the world of Windows, this is not enough. We need a GUI – a graphical user interface. Without this, we would have to compile and debug our program using text commands, easy for us DOS kids, impossible to ask of the Windows generation. A GUI allows us to execute those commands by clicking on icons instead of typing commands. A program that has all of these elements – text editor, compiler and GUI – is called an Integrated Developer’s Environment, or IDE. A good free IDE is rare, but our friends at GCC have an excellent one, and we will use it.

Lets get us an IDE…

Downloading the IDE

1. Go to the following URL:
http://www.bloodshed.net/dev/index.html
2. Click on “DEV-C++” (on box at left)
3. Scan down about half-way to “Downloads” and look at the first download marked:
Dev-C++ 5.0 beta 7 (4.9.7.0) (10 MB) with Mingw/GCC 3.2
4. Click on “Download from SourceForge”
5. Choose one of the mirror servers by clicking an icon on the right-most column. (It doesn’t really matter which server you pick)
6. A new web page should load, and a warning should pop up. Click the “SAVE” button.
7. Make sure you remember which directory you are saving it to. You don’t want to have trouble finding it later.
8. Let it download – it is 14Mb so it will take some time.

Unpackaging the IDE

Once the file has completely downloaded, find it using MyComputer. Double click on the file to unpackage it. Answer any questions it may have, and let it go to work. It will unzip the files as needed.

Setting the IDE

The IDE program is called Dev-CPP. It will set itself up in a directory of the same name. Find the program (devcpp.exe) and double click to run it. It should show a windows-like environment much like this Word program.

Read and then close the tip of the day.

To set up the compiler to work properly, we have to change some settings:
- pull down the “tools” menu
click “compiler options” - “directories”- “C++ includes” (NOT “C includes”)

- you see two white text boxes, one large square one, and one small rectangular one beneath. Beside the smaller one is a button with three dots (…) . Press it.

- click on the directories until you get to xxxxx\Dev-Cpp\include\c++\bits (The xxxx refers to whatever directory or drive you chose to install the program. Mine, for example, says C:\Dev-Cpp\include\c++). Press OK.

- the directory you chose will now appear in the small text box. Now click the “Add” button to add it to your list in the upper text box.

This is to tell the compiler where to find special files called include files. We will learn about include files much later, but for now we need them. Repeat the process to add two more directories:

xxxxx\Dev-Cpp\include\c++\mingw32
xxxxx\Dev-Cpp\include\c++\mingw32\bits

When you are finished, the upper text box should look like this:

xxxxx\Dev-Cpp\include\c++
xxxxx\Dev-Cpp\include
xxxxx\Dev-Cpp\include\c++\bits
xxxxx\Dev-Cpp\include\c++\mingw32
xxxxx\Dev-Cpp\include\c++\mingw32\bits

Running a test C++ program

Now we can try running a test program:

- pull down the “file” menu and click the “open” tab. In the Dev-cpp directory there are several subdirectories. Choose the “Examples” subdirectory.
- Choose the “HELLO” subdirectory
- Open the file “hello.dev” (NOT hello.cpp)
- The C++ program appears on the screen. A project tree appears in the window on the left (there is only one branch because this is a simple program). Some useful tabs appear at the bottom for debugging purposes.
- From the menu at the top of the screen, choose “Execute”. Before we run the code we must compile it. (You can try clicking on “run” – the computer will warn us that there is nothing to run yet!) Click on “compile”.
- Now we must wait for the code to compile. Compiling can take seconds, or it can take minutes. Be patient. Your hard drive should buzz while the code is being built and saved on disk. If you look at the bottom left corner, a section is showing the number of errors detected, and allows us to abort (in red) . Don’t press this – it is only if we change our mind and want to stop the compile.

- If you did everything right, the compiling stage should finish and we get back to our main screen. If something went wrong, then you will see a list of errors and warnings displayed at the bottom.

- If there are no errors, press the “execute” tab and then choose “Run”. A black screen should appear with a printed message. Not very exciting, but at least it works. Press “q” then <enter> to end the program.

- If there are errors, then very likely it has to do with how you set up the “include” files. Review very carefully the steps in “Setting the IDE”.

When this file works, close it by clicking “file” and “close project” (NOT just “close”). For fun, try some of the other examples (remember to click on the *.dev files and not any of the others) compile them and then execute them. Close any project first before opening another. You may find that some of the examples do not work properly. As long as most of them work, you can be assured that you have set up your IDE properly.

Now you are ready to try creating your own c++ programs.
 
Last edited:
Lesson 3: Getting to know the IDE (DAY 1)

The two C++ IDEs used in this course are almost identical, but I will go over them separately.

To create a new project…

In MS Visual C++

· Open the MSVC IDE.
· click FILE – NEW – then choose the “Project” tab.
· Under “project name” (text box at right) type “test”.
· The text box below this (“location”) shows the directory that the file will be saved in. Click the button at right to change the directory to your h: drive. The IDE will automatically save all your project work to this directory.
· The window on the left shows all of the possible kinds of applications we can create. Click on “Win32 Console Application”. Click OK.
· In the next window, choose “An empty project”. Click Finish.
· Click OK
· The foundation for your project is set. Now you must add a file to your project. To do this, click the “Project” tab and choose “Add to Project” and then “new…”
· Click on “C++ source file”. Type in a name (“test”) for your file in the text box on the right. Click OK.

In Bloodshed Dev-C++

· Open the Dev-C++ IDE
· click FILE – NEW – PROJECT
· type the name of your new project (“test”) in the Name text box (at bottom left).
· click Console Application. Click OK
· Now choose the directory to save your project. Click SAVE when done.

Navigating the IDE

Both the MSVisual C++ IDE and the Bloodshed Dev-C++ IDE have a similar layout. Let’s look at the MSVC layout:

Navigating the IDE

Notes:
1. The name of the project is shown at top. The project may contain many files, but the current one being worked on is shown in brackets (“test.cpp”).

2. These buttons are shortcuts for building and executing your program. Place your mouse pointer (called a cursor, actually) over the buttons without clicking on them. Their purpose is written at the bottom left of the screen.
· the compile button compiles the current file only.
· the build button compiles all files in the project and links them together. For now at least, our projects will only contain a single file.
· the execute button runs your program, once it has been compiled.
In general, you can just use the “!” icon. The IDE will let you know if your code needs compiling.

3. This is the project window. It will either show the project’s files or the project’s classes, depending on which tab is chosen at the bottom of the window. We are not concerned with classes until later in the course. Lets look at the project files.

There are three kinds of files in our “test” project. They are:
· source files: These are your “program files”. There may be one file in a simple project, or there may be many. If we write several source files, the compiler will have to link them together.
· header files: These files contain functions written by the pros to help us do things. Math functions, printing functions, graphics functions – there is a huge library of these at our disposal. We call them header files because we include them at the head of our program. They are also called include files, for the same reason. We will learn about these files soon, and will write our own versions of them - later.
· resource files: These are files that are needed by our program, but don’t fit in the above categories. Bitmap files and sound files are common.

4. This is a message window. It shows any messages the compiler has for you.
· By clicking the “Build” tab, you will get any errors encountered when compiling your program.
· By clicking the “Debug” tab, you will see messages given when in “Debug” mode. In this mode, you can trace the value of a variable, or step through the program one line at a time. This is a very useful feature of any IDE, and we will get to know it later.

For now, we will not be in Debug mode. We choose to be in “Release” mode. This mode is so called because you are compiling the code to be “released to the public”, whereas in Debug mode, you are still making adjustments and checking for errors.
 
Last edited:
Lesson 4 Our First Program (Day 2)

Using your IDE, create a project called “favourite” . Set your program to “Release” mode (if you’re not sure how, please ask!).

In MSVC we begin with a blank screen, but the Bloodshed IDE will automatically insert some necessary code onto the screen to get you started. Either way, put the following code into your editor window.

Code:
#include <iostream>
#include <stdlib.h>

int main(int argc, char *argv[])
{
     system("PAUSE");	
     return 0;
}
[/QUOTE]

The only difference between the two IDEs is that the MSVC compiler will automatically pause at the end of the program, whereas the Bloodshed compiler will not. The line system(“PAUSE”) is needed with the Bloodshed compiler, but not in MSVC. When the above code is run in MSVC, it will pause for a keystroke twice.

What does the code mean?

Considering how little the code does, there is a lot of writing! Here’s what it means:

The first two lines tell the compiler that we will need to include two header files called “iostream” and “stdlib.h”. These two header files contain the necessary code for doing standard things like printing and clearing the screen. There aren’t many programs we will write that won’t do at least that, so these files are almost always included with our program.

The main program is actually named main. Other than to say that this line is basically the title of our program, we can ignore this line for now

The curly braces { and } define the beginning and end of the program. Inside the braces, the only actual code is two lines. The first line (system..) tells the computer to pause and wait for a key to be pressed. As you know from BASIC, this is such a common necessity in programs that someone wrote a function to do this automatically. The second line (return…) tells the compiler to let us return to Windows because we are done (as soon as the user presses a key). This is a classic example of something that BASIC did automatically for us – we never even thought about it – but C++ doesn’t do it unless we ask it to.

Try compiling, then running the program. Exciting stuff!

Let’s add some meat and potatoes to our program:

Code:
//   	My first program
// 	This is a comment

#include <iostream>			// these are the
#include <stdlib.h>			//  include files
using namespace std; 			// I’ll explain this later

int main (int argc, char *argv[])		// program “title”
{ 	
    int number;	  
    number = 3;
    cout << "My favourite number is "<< number<<"  \n\n";
    system("PAUSE");			// not necessary in MSVC
    return 0;
}

[/QUOTE]

We have added a few things – comments, and some code. Notice the colour coding done automatically by your IDE. See if you can guess what the code does. Compile it, run it and see if you are right.

Comments

Comments are text that are ignored (in fact erased) by the compiler. They are useful for giving instructions to the reader, but do nothing to the program itself.

Comments are given two ways:
- Two forward slashes // This will “comment out” any text to the right of it, on that line only.
- slash-star /* and star-slash */ The slash-star will comment everything after until it meets the */ symbol. In other words, they act as a kind of begin-comment and end-comment pair.

Commented code is coloured and italicised the moment the comments are typed in. Try them both out to see the difference.

Variables

Unlike in BASIC, variables in C++ have to be declared before they may be used. To declare a variable, the syntax is

Code:
datatype	variable1, variable2, variable3 [etc.];

for example, 
    int  x;		
    int  x, y, z;
    char  letter ,  another_letter, yet_another_letter;


The cout function

The C++ print function is called cout (pronounced “See-Out”). This is short for “Console Out” (the console is the little black screen that appears when the program executes). The “<<” signs are meant to be arrows indicating the direction of flow of information. First the words “My favourite…” go out to the console, then the number variable is next, then “\n\n”.

Escape Sequences

The last characters (\n\n) are called escape sequences. Escape sequences are sets of characters (usually two or three) that perform special functions. Try changing it to “\n\n\n”. Compile and execute again – any guess what this particular escape sequence does?

See Appendix A – Common Escape Sequences

The Semicolon

Most lines of code end with a semicolon ; The semicolon ; indicates the end of a statement. This has an advantage: we could write our cout statement like this:

Code:
cout << "My favourite number is "
        << number 
        <<"\n\n";

The compiler doesn’t care – it only looks for the semicolon to end the statement.

The editor doesn’t force you to put anything anywhere. In fact, one of the first things done on compile is to remove all whitespace (spaces, comments, carriage returns, etc). Your code is converted to one long line with no spaces or returns, like so:

#include <iostream>#include <stdlib.h>using namespace std;int main (int argc, char *argv[]){int number;number = 3;…and so on.

This fact allows us to arrange the code just about anyway we like. For readability of course, we choose to space things out. In this course we will stick to a standard way of writing code. If you take other courses further down the road, you may find variations on that standard.

One nice feature of a good IDE is that the indenting is done automatically. Once you have toiled through multiple indents in BASIC, we figure we can let the machine do it for you.

Input and Output

Most programs will involve input (from the keyboard) and output (to the screen). This is accomplished using the cin and cout functions. Whenever we use these functions, we must add the include file iostream to our list at the top of the code.

cout is the equivalent to PRINT in BASIC. It follows the following format:

cout << “Print a string like this” << “and variables like this” << x << y << z;

Printing a single character requires single quotes, like so:

cout << “To print a single letter, use single quotes: “<< ‘a’;

Adding escape sequences will help format the output:

cout << “This is a tab\t and this is a backspace\b and this is a new \n line”;

cin is the equivalent to INPUT$ in basic, except it does not print a question. That is the job of the cout function.

cout << “Enter a number”;
cin >> userNumber;

Notice the arrows point in opposite directions. The arrows symbolise the direction of flow of information. In the case of cout, the arrows (together called the extraction operator) indicate that the string “Enter a number” are sent out to the monitor. In the case of cin, the arrows (together called in insertion operator) indicate that the user’s answer gets inserted into the variable userNumber.

Close your workspace and open a new one called IOProblems. You will put

Problems

1. Create a program that asks the user to pick a number. When the user responds, tell the user that this is also your favourite number.

edit: Thanks to Bubba Gump for fixing an error in one of the codes
 
Last edited:
Lesson 5: Data Types (DAY 2)

There are several data types available in C++. We have seen many of them before. The main ones are int (integer), float (“single precision floating point” – equivalent to single in basic), double (for more digits of precision than a float), char (for characters) and bool (for boolean values). Sometimes you will need to know the size and boundaries of each data type, so here is a table:

Code:
Data Type	|           Values                 |   Digits       | Size (Bytes)
	         |   From              To          |  Precision   |
  bool	            false (0)    true (not 0)	   -	                1
   char	        0	        255	            -	                1  
    int	          -2 million	    2 million	            0	                4
   float	 -3.4E+38	     3.4E+38	   7	                4
  double	-1.7E+308	    1.7E+308	  15	                8

Characters are stored using ASCII code, which explains their numerical values.

Integers can be further defined as signed (as in the table above) or unsigned (all positive values - ranging from 0 to 4 million), short (taking up two bytes only) or long (default). Usually we don’t use these qualifiers since ordinary int (signed and long by default) will usually do.

The Boolean data type (after George Boole, mathematician that “invented” logic 1831- 1878) is new to us. Programmers use this data type so often that the designers of C++ decided to put it in. Furthermore, the compiler recognises the values true and false automatically so that the programmer does not have to explicitly define these values in their program. In general, false equals zero and true is not zero.

One HUGE advantage of C++ over BASIC is that once a variable has been defined, it will have that data type for good. No data type suffixes are need. Gone are the %, $, !, & and # symbols of BASIC infamy. The only problem is that the user has to always be aware of the data type of each variable, since they aren’t labelled anymore. Good variable names are a must to prevent confusion.

Code:
myage 		//this variable is probably an integer
myMiddleInitial	//this variable is probably a character
bigDoofus		//who knows what this is…

The sizeof( ) operator

The length of a piece of data is a reflection of how much memory space it takes up. For example, the number 1 can be stored in many different ways, but each way will use (or rather waste) different amounts of memory.

char x = 1; takes up one byte of memory
int x = 1; takes up four bytes
float x = 1 takes up four bytes
double x = 1 takes up 8 bytes

We always want to be efficient, but practical. Unless we are really crammed for space, we would use the second option, the integer. The character data type would use less space, but it’s confusing to use a character variable to represent a number, isn’t it?

Here’s how a 1 would look in the memory in each case:

- as a character: 0000 0001
- as an integer: 0000 0000 0000 0000 0000 0000 0000 0001
- as a double: …well… you get the idea.

The integer looks like a waste of space, but we won’t worry too much about wasting a byte or two of space. Even so, double and float should only be used for precision values like pi.

Every CPU is slightly different about how much space it allocates for different types of data. If you need to know how much memory is used for a given variable, just use the sizeof( ) operator. It’s use is intuitive:

int x = 7;
cout << “The variable x uses “<< sizeof( x ) << “ bytes of memory”;

The answer should be 4 bytes of memory, but again, it depends on the CPU.

Defining and Initializing a Variable

Code:
To define a variable, is simple:
	int x;		// defines x as an integer
To initialize a variable, we give it a value:
	x = 92;

When we execute the first step, the compiler finds space in memory for the variable x (it shouldn’t be difficult – it’s only 4 bytes). When we execute the second step, the compiler places the value 92 in that spot in the memory.


Unlike in BASIC, in C++ the computer will not give any value to a variable if you do not ask it to. BASIC initializes all variables to zero by default. In C++ your variable will have whatever value was left in that memory location the last time someone used it. You have to remember to initialize it yourself or your variable will contain crazy numbers.

For this reason it is extremely important that you aren’t lazy when programming in C++. Little things like uninitialized variables will kill you in C++, and as an error it can be very tricky to find.


Problems

1. Create a program with that declares two integer variables. Do not intialize them. Print them out. What are their values?
2. These values seem random. Why did the compiler “choose” these values?
3. In the same program declare two character variables. Print them out without initializing them. What do you see?
4. Print out the address of each of these variables by using the “address of” operator, &, like so: cout << “the address of x is at “<< &x;
5. The addresses are given in hexadecimal. List the addresses of each variable.
 
Last edited:
Lesson 6: Control Statements (DAY 3)

Control statements are used to control the flow of a program. The if and the switch statements are selection statements (also called conditional statements). They select the path that the program will take depending on certain conditions. The for loop, do loop and while loop are all iterative statements – they cause the program to iterate (repeat) a section of code. Finally, the break, continue and goto statements are jump statements, which can be used to get the program out of a loop. P.S. : goto statements are forbidden in this class.

In all cases, code blocks are delimited by braces { }. This eliminates the need for a ENDIF or LOOP or NEXT statement as in BASIC.

The if statement

This follows pretty much the same as with BASIC:
Code:
if (condition)
}
     // put code here
}
else if (othercondition)
{
     // more code here
}
else
{
    // last bit of code here
}

Notes:
1. the conditional expressions are put in round brackets ( )
2. code blocks are defined by curly braces { }
3. Notice that the first line does not end with a semicolon. This is because the if doesn’t finish until we get to the last brace.
4. unlike in BASIC, else and if are two separate words, always.

If a code block has only one single line to execute, it need not be placed in braces:

Code:
if (condition)
   a = 3;	// ****only one line of code here – no braces needed
else
{
   a = 6;	// two lines
   b = 75;	//  need curly braces
}

The switch/case statement
This is identical to the SELECT/CASE statements in BASIC:
Code:
cout << “pick a number from 1 to 4”;
cin >> num;
switch(num)
{
case 1:
     cout << “Not a bad number.  A little thin perhaps”;
     break;
case 2:
    cout << “Now we’re talking a number!”;
    break;
case 3:
    cout<< “Please!”;
case 4:
    cout << “Yawn.  Next!”
    break;
default:
    cout << “Read the instructions!  Hello, McFly!!”;
}

The switch/case statements are a little tough to get used to, but they are perfect to use with menus.

Notes:
1. The break statement stops the flow from continuing from one case statement to the next. For example, case 3 has no break statement. If the user picks the number 3, the computer will respond with “Please! Yawn. Next!”.
2. The default case is all cases that haven’t been mentioned. This is essentially what the else statement does for an if statement. Default is usually used so the computer can respond to illegal values entered by the user.

The do loop and the while loop
Code:
do 
{
   // do stuff here

}while(condition);

Notice that the last line ends in a semicolon. Recall that all C++ statements end with either a semicolon or a brace.

This do loop will loop as long as (i.e. while) the condition is true. Note that this is the opposite of a do loop in BASIC, which loops until a condition is met.

A do loop will always execute the code block at least once, since the condition is not checked until the end of the block. If this is undesirable, we use a while loop:
Code:
while(condition)
{
  // do stuff here
}

Note that there is no semicolon needed, since the block now ends with a brace.

The for loop

The for loop looks a little different than in BASIC, but it has all of the same elements in it:

Code:
for (i=0; i < 10; i++)
{
   // do stuff here
}

there are three parts to the for loop statement.
· i=0, sets the initial value of our counter, in this case i.
· i < 10, is our control condition. The loop will continue as long as the condition is true.
· i++, is identical to saying i = i + 1. This mathematical expression is so common in loops that the makers of C++ decided to give it an abbreviation. Here are some other abbreviations:

Code:
i--	(decrement)
i+=2  (increment by 2 – an abbreviation of i = i + 2)
i-=6  (decrement by 6 – an abbreviation of i = i – 6)
i*=2   (multiply by 2 – an abbreviation of i = i * 2)
etc.

We could alter these three elements of our loop as desired:

Code:
for(i = 10; i < 50; i++)	//loops from 10 to 49 (as long as i < 50)
for (i = 10; i > 0; i-- ) //loops from 10 down to 0 (as long as i > 0)
for (i = 1;  i < 10; i+=3) // i becomes 1, 4, 7  (as long as i < 10)

Assignment Statements vs. Conditional Expressions

In BASIC, an assignment statement assigns a value to a variable:

Code:
    mynumber = 88

A conditional expression looks the same, but has a whole different meaning.

Code:
   IF mynumber = 88

In the first example, mynumber IS 88, whereas in the second example, we are asking IS mynumber 88? This produces an ambiguity, that is, the expression could mean two things, depending on the context. C++ does not allow this ambiguity, and avoids it by using a different symbol for “relational equality”:

Code:
mynumber = 88;		// sets mynumber to 88
mynumber == 88;	// determines if mynumber is 88

The first symbol (=) is called a arithmetic operator, because it is used in arithmetic expressions. The second symbol (==) is called a relational operator, because it is used to determine the relationship between the left side and the right side (i.e. are they equal?). Other important operators:

Code:
Relational Operators
> (more than)	
< (less than)	
>= (more than or equal)
<= (less than or equal)		
!= (not equal to)		
== (equal to)		

Logical Operators:
&& (And)
|| (Or)
! (Not)

Quick Summary:

1. There are two kinds of control statements: selection statements and iterative statements.
2. Code blocks begin and end with braces { }
3. Use break to get out of a code block.
4. All c++ statements end in either a semicolon ; or a brace }
5. A control statement (if, for, do) does not really end until the last brace.
6. C++ offers shortcuts such as the increment operator ++, the decrement operator --

Exercises

1. Use a for loop to print out the numbers:

a) 14 to 20 inclusive
b) –10 to 10 inclusive
c) -3, -5, -7, -9

2. Ask the user to enter a number. Use if statements to inform the user if the number is odd or even.

3. Modify your code for #2 to determine if the number is odd or even and positive or negative.

4. Read question #3 carefully. Explain why it is an ambiguous question, and like poor programming, could end up being misinterpreted. What device would a programmer could use to eliminate the ambiguity in the question?

5. Ask the user to enter a number. Use a switch/case statement to give three different responses to the user based on the number, and one default response.

6. Use a while loop for the following code. Ask the user for a number. Keep asking for that number until the user enters a 7.

7. Use an if and a break to modify #7 so that it gives the user 3 tries to get a 7.

8. An example of an expression using some of these relational and logical operators is:

while (i <= 8 && (i==3 || i > 4))

a) This is a difficult expression to read! Write it out in English.
b) Which are the relational operators?
c) Which are the logical operators?
d) What possible values of i will make this expression true?
e) Why are the inner brackets needed?
f) Give the possible values of i with the inner brackets removed.
 
Last edited:
Lesson 7: Arrays (DAY 4)

How do we get a string if there is no string data type? The answer lies with arrays. A string is simply an array of characters. Defining an array is simple:

int x[3]; // an array of 3 integers
char a[6]; // an array of 6 letters
float p[4]; // an array of 4 floats

Notice the square brackets rather than the round brackets in BASIC. Each array is made up of elements. The elements begin with element 0, so be careful:

x[0]= 7; //x[0] is the first element
x[1] = -5;
x[2]= 42; //x[2] is the last (i.e. third) element.

Arrays, like regular variables also can be defined now…
int x[3] = { 4, 32, 99};

… or later:
int x[3];
x[0] = 4;
x[1] = 32;
x[2] = 99;

Obviously defining an array right away is easiest, but sometimes the values are not known right away.

As a rule important variables (or arrays) should be defined at the beginning of your code, like DIM statements in BASIC. Throw-away variables (like counters) can be defined just before they are needed. Unlike BASIC, all variables in C++ must be defined or the code will not compile!

Printing Arrays

An array cannot normally be printed in its entirety. It is printed one element at a time.

int x[3] = { 4, 32, 99};
cout << x; // will print gibberish
cout << x[1]; // will print ?

To print all elements in an array would be an ideal job for a for loop.

Character Arrays

Back to our idea of strings, a string is an array of characters. But since this kind of array is somewhat special, there are some differences in its properties:

First of all, character arrays can be defined as before, all at once:
char word[10] = {‘h’, ‘e’ , ‘l’, ‘l’, ‘o’};

…or one letter at a time:
char word[10];
word[0] = ‘h’;
word[1] = ‘e’;
… and so on.

A much more convenient way of defining a character array is this:

char word[10] = “hello”;

But defining a string and initialising it later is illegal:

char word[10]; // define word as a string
word[10] = “hello”; // error!

Why is this illegal? Because the compiler thinks you are trying to stuff the whole word “hello” into the tenth element of the word array. word[10] can only contain a single letter, so the compiler will give an error message.

The terminator

Try defining a character array and then initialising it the hard way – one character at a time:

char myword[10];
myword[0] = ‘L’;
myword[1] = ‘a’;
myword[2] = ‘m’;
myword[3] = ‘p’;

Then print the array out. What happens? Why?

Remember, C++ does not reset variables. Let’s take a close look at the variable myword:

First, myword is given 10 characters. each character takes 1 byte of memory, so it looks something like this:

[0][1][2][3][4] [5] [6][7][8][9]
[3][@][t][&][%][+][#][k][>][J]

The numbers at the top represent the element numbers, and I’ve filled each memory cell with random junk.

Next, we fill in myword one cell at a time, until the first four letters spell “Lamp”:

[0][1][2][3][4] [5][6][7][8][9]
[L][a][m][p][%][+][#][k][>][J]

Now when I print myword, the computer prints out all ten letters, including junk that I never intended to print! How can the computer possibly know that I only want the first four letters out of the ten? The answer lies with a special character called a terminator.

A terminator is a special character that lets the computer know that we are at the end of a string. In C++ the terminator is called the “NULL” and it looks like a backslash and a zero (it is an escape sequence, if you remember those). We place this null character at the end of our intended word, like this:

myword[4] = ‘\0’;

[0][1][2][3][4] [5][6][7][8][9]
[L][a][m][p][\0][+][#][k][>][J]

Now when we print myword out, the computer will stop at the letter p.

Surely, you say, there is an easier way of inserting letters into a string? The answer is yes there is, by doing it all in one shot:
char myword[10] = “lamp”;
Doing it this way, the computer knows the what the whole word is, and it will obligingly place the terminator in for you.

Finally, a string that is initialised right away can be automatically sized by the compiler:

char myword[] = “lamp”; // this will be given 5 bytes of space

One more curiosity about characters and strings. The difference between the single quotes and the double quotes is that single quotes enclose a single character, but double quotes imply a string, and so a terminator is always added to the end. For example, the letter ‘A’ is one byte long. But the letter “A” is two, and in memory it would appear as two characters, A and \0 .

Exercises

1. How many bytes of space are required for the following arrays?
a) int age[4];
b) char word[13];
c) float price[8]

2. Use the sizeof( ) operator to check your answers in question #1.

3. What is the maximum number of values (numbers or characters) you could store in each of the arrays in question #1?
a)
b)
c)

4. Create a program that puts 6 numbers in an array called lottery. Fill the array explicitly with the numbers 5, 8, 14, 25, 26, 40. Ask the user to pick 6 numbers. Fill an array called userpicks with these numbers. Print out the user’s numbers and the winning numbers. i.e.

You picked: 4, 6, 8, 9, 32, 44
Winning numbers are: 6, 10, 14, 20, 44, 46


5. Modify your program in #4 to tell the inform the user at the end which numbers matched, and how many matches were found.
 
More Array Practice (DAY 5-6)

1. Create a program that asks the user for a word (25 letters max). Store that word in an array called forword. Take forward apart letter by letter and store the letters in reverse order in an array called backword.

Enter a word: <alphabet>

Your word forward : alphabet
Your word backward: tebahpla

2. This is not an array problem, it is to practice converting to ascii and getting keystrokes.

In c++, there is little differentiation between a character and its ascii value. To get the ascii value of a character:

char letter = ‘g’;
int x;
x = letter; // this does the conversion
cout << letter; // prints ‘g’
cout << x; // prints ascii value for the letter ‘g’

3. Create a program that asks the user for a character, and then print back both the character typed and the ascii value of that character. Use a variable called ch to store the character and use variable ascii to store the ascii value.

4. Create a program that asks the user to type in a string. You are to put the string in a character array called mystring using getch(). When the user has finished typing, print the string out.

Frodo's Note: the getch acts like an inkey. It is used in the syntax:
charvar. = getch();
It will pause the computer and wait for a key to be pressed, and then assigns the key pressed to the charvar.
Side note: The getch() alone does not display the character that is pressed. Used getche() to display the character that was pressed (e stands for echo)


5. Create a program that uses gets() to get a string from the user, and then calculates the length of that string.

Frodo's Note: Make sure you declare a string (if your using more then one character) The syntax is gets(charvar.);
Gets() will save the string INCLUDING SPACES!


6. Create a program that uses cin.getline(charvar, maxcells) to get a string from the user, and then calculates the length of that string.
 
Manipulating Strings in C++ (DAY 7-9)
ASSIGNMENT #1

Combine all of the following programs into one code. Use the switch statement to allow the user to choose which program to run. [2 marks each]

1. Create a program that allows the user to enter a string (use the gets( ) function) and then prints out the string with the spaces removed.

Input: “Hi there how are you?”
Output: “Hitherehowareyou?”

2. Create a program that takes a string as input and switches the letters p and b.

Input: “play ball!”
Output “blay pall!”

3. Create a program that searches for a name in a list of names. Set up an array of strings containing 10 names. Ask the user for his/her name and if it is in the list, have the user notified. Note: Put Prateek on the list.

Input: “Rob”
Output: “Sorry Rob, you are not on the list”
Input: “Prateek”
Output: “Welcome, Prateek, to our exclusive club!”

4. Create a program that tokenizes a string. Have the user enter a string, and have each word in the string stored separately in an array of strings. Print out the string word by word.

String: “Hi how are you?”
Word[0] = “Hi”
Word[1] = “how”
Etc…

5. Create a program that takes in a single character from the user. If the character is a number, print out the square of that number. If the character is not a number, print out the ASCII code for that number.

Enter a character:
Input: “A”
Output: “The ascii value for A is 91”
Input: “9”
Output: “The square of 9 is 81”
 
Last edited:
FUNCTIONS (DAY 10)

Def’n: A function is a separate section of code that performs a specific task. Like a math function, C++ functions return a maximum of one value for every input value.

A function is essentially the same as a subroutine in BASIC. It helps keep the code tidy, and is very useful for common tasks that can be written once and referred to often. You have used functions already, such as getch( ), and isalpha( ). These functions have been pre-written by some engineer somewhere, and sold to Microsoft for use with our compiler. They are proprietary (owned by Mr. Gates) so we are not allowed to peek in and see how they work, for fear that we might improve them and sell our own version. Fortunately, we can write our own functions to make our programs easier to manage. Writing functions to use as building blocks for future programs is called structural or procedural programming.

C++ functions are modeled after their mathematical cousins. Consider the sin function: in a program it would be called like this:

y = sin(x);

This looks surprisingly simple and familiar. It is pretty much exactly how it would be written in algebra class. In this case x is the input value (called a parameter or an argument) and y is the output value (called a return value). We say the sine function “receives an x value” as input and “returns a y value”.

C++ functions can go further than basic math functions. C++ functions can be written to calculate areas and perimeters, but also can clear screens, count vowels and switch ‘b’s and ‘p’s.

Like its math counterpart, a function can receive many arguments, but it can only return a single value. For example, a function that calculates the area of a triangle might look like this;

a = area( base, height)

This function called area takes the base and height as input, and outputs the area, which gets stored in the variable a.

Writing your own Functions
Functions are written outside of (usually after) the main part of the program. To create a function, you need at least three parts:

1. Head of the Function
Every function begins with a title, called the head of the function:

float myfunction (int x, , char ch) // this is the head of a function

float is the data return type. This is the type of data that is going to be returned by the function. In this case, it is returning a float - perhaps the answer to a calculation. There are several return types possible: int, char, float, and so on. One special return type is void. The void return type indicates that nothing is going to be returned from this function (void means “empty”).

The next part, myfunction, is the function name.

Inside the brackets are the parameters of the function. Notice that each parameter has to be declared right away. This is because it will be filled with a value passed on to it by the calling function (usually main) so it needs to know ahead of time what type of value to expect.

To summarize, the above function head example tells us that the function:
· is named myfunction
· takes an integer and a character as input
· returns a floating point number (i.e. a decimal) as output.


Body of the Function

The function body lies below the function head, between braces. In the function body goes the code that gets executed whenever the function gets called.

End of the Function – the Return Statement

Every function has a return statement. The keyword return tells the compiler to return to the main program, or wherever it came from. As well, it indicates what value to bring back with it. Usually this is the “answer” that the function was supposed to calculate.

You’ve written one function already – main( ) is the main function of your program. Let’s write another:

int main() // main is really a function – the ‘main’ function
{
cout << “hello”; // the body of main
saygoodbye(5);

return 0; // main’s return statement
}

void saygoodbye( int numtimes) //this is our new function
{
for (int x = 0; x < numtimes; x++) // the body
{
cout << “goodbye”;
}
return; // doesn’t return anything
}

Likely this program won’t work, because there is one thing missing – the function prototype. As it stands, your code will not compile because when the compiler gets to the line “saygoodbye (5);” it stops because it has no idea what saygoodbye is. It hasn’t read about saygoodbye because the code for saygoodbye is written later – after main. How can we get the compiler to know about saygoodbye before it is called? Two ways:

1. Put the code for saygoodbye first, above main. This will work, but it is a BAD METHOD. Don’t do it. Ever.

2. Leave the code where it is, but warn the compiler ahead of time using a function prototype (GOOD METHOD). A function prototype is just a copy of the head of the function placed above main, like this:

#include <iostream.h>
using namespace std;
void saygoodbye ( int numtimes); //This is the function prototype

Just copy the function title, paste it above and add a semi-colon. (Why doesn’t the function title have a semi-colon already?).

When the compiler reads the function prototype, it is “warned” in advance to search for a function called “saygoodbye”, which it does. It finds saygoodbye() easily where you placed it, and it loads it into memory, so that when it comes time to use it, it knows where to find it.

Fix any bugs if there are any and run your program. Answer the questions below:

1. What does the code do?
2. What is the value of numtimes? How does it get this value?
3. Change the code so that it prints goodbye 9 times.
4. Try printing numtimes in main. What happens? Can you guess why?
5. What value does saygoodbye take as a parameter?
6. What value does saygoodbye return to main?
7. saygoodbye is a void function. What does this mean?

Returning a Value

Oftentimes a function will return a value to the function that called it. For example sin( ) returns to us the sine of a number. To get the value returned from that function, use the following format:

returnvariable = functionname( );

This is natural when you think of a concrete example:

letter = getch( );

letter is a variable you set up to get the result of the getch( ) function. getch( ) gets a character, and stores the character in letter.

Other examples of some fictional functions:

y = sin(x); //sin( ) takes x and returns y
answer = squareroot(49); //answer gets a value of 7
area = square(length); //area = length * length

The function prototypes for each of the above examples might look like this:

float sin( float x); // takes a float value and returns a float answer
float squareroot(int x); // takes an int and returns a float
int square(int l); // takes an int and returns an int

The data types on the left tell us what to expect for the “answer” of the function, and the data types on the right in the brackets tell us what kind of data to put in to the function.

Question: Consider a hypothetical function that takes a character and returns the ascii value of that character. Write the function prototype for such a function.
Answer:

PRACTICE

happy ( )
Create a function called happy( ). happy( ) takes no arguments and returns nothing to main. The sole purpose of happy() is to print out the sentence “I am happy!” once per call. Use this function to create the following output :

Hi how are you?
I am happy!
What’ s new? I haven’t seen you in a while.
I am happy!
Are you sure you’re ok? You keep saying “I am happy”!
I am happy!
“Ok, I’m going to go now.”

square( )
Unlike other arithmetic operations, there is no symbol for squaring a number (eg.x= 7^2). In c++, the only way to square a number is to multiply explicitly (x = 7 * 7).

Create a function square( ) to square numbers for you. In main ask the user for a number, and then call square( ) for that number. Output the result, e.g.:

Please enter a number: 47
47 squared is : 2209

Note that square( ) does not handle ANY input from keyboard or output to the screen. There should be NO cin and NO cout in square(). That is all done in main. Remember – one function, one task. Square()’s only task is to square a number.

Note: square should be able to handle decimal numbers.

power( )
Take square( ) one step further. Create a power( ) function that calculates the power of a number to a given exponent. The number and the exponent should be given by the user.

Discussion Questions

1. Which of the above functions is a void function? What makes it void?
2. Which of the above functions has one parameter?
3. What are the parameters of the power( ) function?
4. What is the return type of the square( ) function?
5. Even though happy( ) is a ridiculous function, the program is better with it than without. Explain (picture how the program would look without using functions).
6. Why are you asked not to have input (cin) or output (cout) in your functions?
 
Last edited:
More Function Problems (DAY 11)

READ THIS BEFORE YOU BEGIN:

1. Functions should be simple. One function, one task.
2. Functions don’t usually (I would say never) give output.
3. Variables in functions are NOT THE SAME as the variables in main, so do not name them the same. Keep the variable names in the function simple, like s or str for a string, ch for a char, etc. The long names like userstring or letter should be used in main.
4. Don’t forget to write the function prototype before main!

Try writing your own version of the standard functions:

1. isdigit() : This functions return true if the character sent is a digit. Write your own version. Some pointers:
· take a character and return a Boolean value.
· use getch() to get the character from the user in main, then print out the result (“t is not a digit”, “4 is a digit”, etc).
· loop it until the user hits the return key (‘\r’) to quit.
· you can’t cheat – don’t use the real isdigit() in your function. Find some other way to determine if the character is a digit.

2. len() : Remember this BASIC function? LEN determines the length of a string. Create your own version:
· use cin.getline() to get a string from the user
· send the string to len() which counts the characters in the string.
· len() returns the number of characters.
· print out the answer in main. NOTE: you can do this the long way:

int x;
x = len(mystring);
cout << “ The length of the string is “<< x;

But there is a much more direct way of doing this. Can you think of how it can be done in one step instead of three?
 
lol.

Im new here at this board, currently a engineer student myself. Just like to point out that I sure wish I took Computer Sciences in high school.

My advice: Learn the basics (As Frodo here is posting for anyone to read) It will most definately help you throughout your first year of University/College Programming, as teachers often forget that some students have little, or no previous experience with courses of this sort.

My 2 cents.

-PhP_PhoBos
 
Frodo Baggins,
I'm finding your posts very helpful because I've wanted to learn some programming languages.
 
Great stuff! I've been wanting to learn C++. Thanks Frodo & keep it coming! :)

Soy
 
I learned OOP(Vis Java) prior to NON-OOP(C++) and I must say that learning it the other way, C++ first, say, is much much easier. Great idea for a forum post FRODO, let the world share your enlightenment and it shall increase...
 
well written guide, covers almost everything I learned in a full semester of computer science.

Great job frodo!
 
Thank you so much Frodo, I've been wanting to learn C++ for the longest time. I hope you don't mind if I ask some questions about it(I'm a real newb in programming, I've dabbled a little in BASIC but nothing serious). I'm up to lesson 7 and it asks you to tell the user if the number they enter is even or odd, how the heck to I do that? I can program to tell the user if it's negative or positive, but what's the code for even and odd?
 
I believe you mod the number, if it equals zero, its even, if its doesnt eual zero, its not even. as an example

cout<<"enter a number.\n";
cin>>number;

if(number%2==0)
number==even;

else number==odd;
 
Back