Learn Programming And Algorithms with C++

Written By San Saeteurn

What you Need to get Started:

  • A C++ Compiler (You can obtain One from GNU For Free)
  • A Type of Unix Operating System, Some good ones are: Mac OS X, Linus
  • Know how to use Unix (The Command Line) - If you can't use Command Line Unix, check out my Intro to Unix Command Line
  • Strong Computer Skills

  • Introduction

    C++ is a very powerful high level computer programming language. It is probably the most highly used language today. If you want to be a programmer,C++ is the best language to know.
    C++ is what Computer Scientists call an OOP Language, or Object Oriented Programming Language. Most high level Languages that people use today are OOP Programming Language. This is because the way OOP Languages are organized. Before OOP, programs were executed sequentially, or line by line. Commands are executed one by one unless a command is reached that tells the processor to jump to another line in the program. The Original C language was not OOP. Some Examples of OOP Languages are:
  • Java (Not Java Script)
  • Basic
  • Pascal
  • Objective C
  • What is OOP, really:
    OOP Language share one common thing, the structure of the language. Unlike non-OOP, these languages revolve around things called Objects. These Objects are essentially a grouping of methods/functions and properties.

    Methods/Fucntions:
    Methods/Functions are specialized code that was designed to do a particular job. Example: Lets say you have an Object called Human. The Functions/Methods of Object Humans are what it can do. Like Walk, run, talk, drive a car, etc. It is what the object does.

    Properties:
    The Properties of an Object are the characteristics of it. Referring to the above example of Object Human. The properties of a Human are eye color, number of arms, number of legs, a head, etc. The Characteristics of the Object. Often times, the Methods/Functions of an Object are used to alter the Objects Properties.

    Lets Look at an Example of how this would work:
    	//All of your codes should contain a header like this.  It should include your name, the date created, date modified
    	//CopyRight Stuff, and a Description of it's use.
    	//Also, when you define a header file, always put in the following code:
    	//#ifndef FILE_H
    	//#define FILE_H
    	//And at the End of the Header File, put #endif
    	/***
    	Created By: [Your Name Here]
    	Date Created: [Put Date Here]
    	Date Modified: [Put Date Here]
    	CopyRight: [Whatever]
    	Program Description Goes here
    	***/
    	#include <string>
    	#include <iostream>
    	using namespace std;//Because the original string.h and iostream.h has been set to standard,
    			    //you must enter this line under it to show that it is standard (std)
    	/***
    	Class Greeting
    	***/
    	class Greeting//Class Definition (A Class is the Representation of an Object in C++)
    	{
    	    private://The Things under 'private' are not accessible by the outside
    		string greet;//A Property of Class Greeting
    	    public://The Things under 'public' are accessible by the outside	
    		//This is a Function/Method
    		void displayGreet()//Normally the Body of the Function will be in a separate file with
    				   //extension .cpp and the this would be a header file w/ exten .h
    		{
    			//This Line tells the Operating System to Print the value of greet to the screen
    		    cout << greet << endl;//The end of any Line need a semicolon ';'
    		}
    		//Notice that this function's name is the same as the Class's Name...hmmm
    		Greeting();//This is a Special Function called the Class's Constructor.  This Function is
    			   //automatically called when you instanciate a class
    			   //It is Used to setUp the Class's property values
    		{
    		    greet = "Hello World";
    		}
    		//Notice what's weird about this Function
    		~Greeting();//This Function is called the Class's Destructor Function.
    			    //It is Automatically called when you destroy an instance of a class
    			    //Often times, the comiler would generate a destructor
    			    //function for you class if it is simple.  But don't count on it.
    	};//At The end of all class definitions, you need a semicolom
    	/***
    	The Main Function
    	***/
    	int main()//The Main Function is where you use the classes to run a program
    	{
    	    Greeting gr;//An instanciation of The Previously defined class called 'Greeting'.  Gave it an identifier 'gr'
    			//The Constructor is called when you enter this statment
    	    gr.displayGreet();//Calling the Function 'displayGreet'
    	    return 0;//Tells the CPU that the program ended without any problems.  The '0' mean no problems, a '1' means error occured.
    	}//Notice you don't need a semicolon here, main is not a class, but a function.
    

    Don't be discouraged if you can't follow this program. Copy this program into a file and name it 'main.cpp'. In the Command Line, go to the directory that contains this file and type 'g++ -o Prog1 main.cpp'. This command will compile the code and produce a file called Prog1. For more information on 'g++', type 'man g++'. After it is compiled, type './Prog1'. Observe what happened.
    If the Program has no syntax errors (Errors caused by typos and other things like that: forgot semicolon, missing
    needed command, etc.) then the command line should prompt: 'Hello World'

    Let's discuss how that program works.
    First, you see the the include statements. These statements are used to import code from somewhere. In this case, the standard Library. The values inside the '<' and the '>' is the header file name. Normally, you need an extension '.h' but because this is the standard Library, you put 'using namespace std;' under it. If these are you own header files, it would be in quotes "" instead of the </>. And will need the extension '.h'
    A class was defined with the following command:
    class Greeting//Class Definition (A Class is the Representation of an Object in C++)
    

    Under this Command is an Open Bracket '{'. This is used to enclose the code. It means, whatever you see inside the brackets '{' '}' is associated with the thing above the first open one. The other is a cloase bracket '}'. It means the end. Example: As you can see, under the line
    class Greeting
    there is a '{'. If you scan down, you will see another bracket, '}'. All the lines inside these two brackets are associated with the class Greeting. The lines inside these two brackets define the object. It is the objects properties and functions. Notice the semicolon at the end of the Greeting Class Definition. You must have one of those at the end of ALL of your calss definitions.
    Inside the class definition, there is a 'public:' and a 'private:' These are used to identify which properties and functions are accessible by the outside world or not. There is also a 'protected', which is used for inheritance, but we will get into that later. Right now, public and private is all you need to know.
    Under the 'private:' line, exist a statement that reads 'string greet'. This mean, create a property of class string and name it greet. In these definition, you can't instanciate them. That is what the constructor will be used for.
    Under the 'public:' line, there are several thing. One is 'void displayGreet()'. This is a function declaration, and in this case, also definition. You may notice the bracket following this. The code inside the brackets are associated with the function. In this case, 'cout << greet << endl;'. This statement means print the value of 'greet' to the screen.
    The next funtion is the class's Constructor. It has the same name as the class. Inside this function is where you would set the inital values of the class's properties.
    Below this function is called the Destructor. It has the same name as the Class but with a trailing character '~'. This function is where you tell the Operating System that you are done with this memory and that it is available again. If you don't do this, you will run out of memory and your progrram will slow down and eventually crash when it has run out of memory. Every peice of data you instanciate must eventually be destroyed. That is what your destructor function does. It is automatically called when you want to delete it. This is why Windows Operating System is slow and crashes all the time. They have bad Destructor functions.
    Now that we have talked about the class Greeting, lets look at the Main function. This function if the 'main' part of the program. This is where the program begins execution. This is where you tell the program what to do. In this case, print the text 'Hello World' to the screen. Notice, the main function contains 'int' before it. This is the return type. Functions, like in MATH, can return values. You have to define the type there. So, somewhere inside the main function, there is going to be a statement that reads 'return [int value]'.
    Inside the main function, the first line is 'Greeting gr;'. This line is instanciating an instance of the Class Greeting and naming it gr. The Constructor is called when you instanciate an instance of a class.
    The next line reads 'gr.displayGreet();'. This line is calling the function 'displayGreet()' from the instance 'gr'. Now, when you call a function, the code that you defined it with will be executed until you reach the ending bracket. In which case, it will jump back to where you were.
    The last line reads 'return 0;'. This is telling the function to stop executing and go back to where it was before it was called with the value speified (in this case, a 1). Since the function was called when the program started, this statement will exit the program!
    Before We Start Coding, you Must Understand the Following:
    Indentifiers - The name given to a Data Type, ex. 'int i;': Defines an integer and names it 'i'. When you want to access this value, you use 'i'.
    Data Types - A Type of Data, ex integers, strings, Greeting.
    Primitive Data Types - Predefined Data Type, they are: integers (int), characters (char), Booleans (bool), doubles (double), and Floating Points (float).
    Identifiers:
    A name you (the programmer) assign to a value. This makes your code easy to read and understand. Often times, you don't want to use a literal, or actual number. Like if you want to add two numbers together that a user inputs. You could instanciate three integers (int op1 - operand 1, int op2 - operand 2, and int ans - answer) and set there values to the value of the user input. If user enter 1 + 2, op1 will become 1, op2 will become 2, and ans will become 1 + 2 (which is 3). This gives you programs flexibility, and most you have to.
    Not all names are allowed. Some name (like for, if, return, goto, int, atoi) are preset, you indentifiers must began with a number (0 - 9), letter (a - z, or $,&,_). IT IS CASE SENSITIVE. Meaning that area is not the same as Area and AREA and aRea. These are all different and don't refer to the same value.
    Data Types:
    A Type of Data. Data types are the objects in the program. Like in the above example, Greeting would be a new Data Type that you defined. There are predefined data types called the Primitive Data types.
    Primitive Data Type:
    These are the predefined Data Types. They include: integers (int), characters (char), Booleans (bool), doubles (double), and Floating Points (float). An integer is a whole number, NO DECIMALS. A Character is a character (you know a letter or other symbol, like %,k,8,* ,etc.). A Boolean is a true false thing. It has only two values, true or false. A Double is a decimal number. Not just the fraction part, any number that cpntains a decimal, ex. 3.1415, .00972. A Floating point is the same as a double except not as long. The maximum value a Float can represent is smaller than a double. Only use if you are conserving memory and you know you don't need a large decimal number.
    Comments
    I have been using them, but have you noticed what they are? If you look at the sample codes I have written, a lot of the text are regular english with two slashes '//' before them. These things are called comments. They are used to help readers understand the code. Comments tell the reader what a particular part of code does. You can create comments with the double slash '//' or, to do a large comment that is multi lines you use '/* */'. Open the comment field with a '/*' and close it with '*/'. All the text in between will be comments. These are usually used to document code. Rather than telling what a specific part of code does, you tell what an entire function or class does. It gives the big picture on it and tells how to use it.
    Now Let's Look at the 4 Main Ideas of Programming:
  • Sequential
  • Branching
  • Looping
  • Methods/Function Calls
  • Sequential:
    Executing Code Line by Line.
    ex.
    	int i;//Declare variable i
    	i = 0;//set i to 0
    	i = i + 1;//increment i by 1
    	cout << i << endl;//print the value of i to the screen via standard output
    
    Branching
    Branch to another line of code based on the results of a Comparison (Comparison's become booleans: true or false). These are the if statements. They have to be enclosed in brackets too.
    ex.
    	int i;//Instanciate an integer and call it 'i'
    	cin >> i;//Prompt the User for an input value and store it in 'i'
    	//the results of 'i == 0'is either true or false.  So we can actually assign this to a
    	//Boolean value:  bool toZero = i == 0; is valid!
    	if(i == 0)//Compare 'i' with the value 0.  If they are the same, execute the
    		  //code inside the brackets, otherwise, skip it and go on.
    	{
    	    cout << "You Entered a 0!!" << endl;//Display the 'You Entered a 0!!' to the command line
    	}
    
    There are also the switch statements, but they are kind of useless. They are only used to simplify a large if-else statement. You can do anything without the switches. But what if you want to make multiple decisions. Like, go to movies, if theatres are closed, go shopping. If stores are closed stay at home and watch movies. If have no movies, commit suicide. These are the nested else's. An if-then-else statement. These could go on and on and on and on. Let's take a look at one:
    	int i;//declare i, automatically default as 0
    	cin >> i;//Prompt user input and store it in i
    	//Checks the value of i
    	if(i == 0)
    	{
    	    cout << "You suck" << endl;//Do this if i is equal to 0
    	}
    	else if(i == 1)//Notice this one has no brackets!!!!!!!!!!
    	    cout << "You are cool" << endl;//Do this if i is equal to 1
    	else if(i == 2)
    	{
    	    cout << "What the...?" << endl;//Do this if i is equal to 2
    	}
    	else
    	{
    	    cout << "I am confused. :-(" << endl;//Do this if i is not 0, 1, or 2.  If i is something else!
    	}
    
    Technically, you don't need open and close brackets if it is followed by one line, but, it is good habit to always include them anyway. Better safe then sorry.
    Also, te thing that goes inside the comparison place 'if(comparison place)' can be any boolean value: a 'true/false', or even 'bool hi = false; if(hi)' is legal. You can even put number values: if(2) or if(0). Any positive value greater than zero is considered to be true. A 0 means false. If you haven't already figured out the standard syntax of an if statement, it goes like this:
    	if(boolean)
    	{
    	    ...code...
    	}
    	else//This part is optional
    	{
    	    ...More Code...
    	}
    	/**************************/
    	//Is this LEGAL?????????
    	if(boolean)//	#1
    	{
    	    if(boolean)//	#2
    		if(boolean)//	#3
    		    ...code...
    		else//This goes with #3
    		{
    		    ...code...
    		    //Is there an else for this if?
    		    if(boolean)//	#4
    		    {
    			...code...
    		    }
    		}
    	    //This else goes with if #2 not #4, why?
    	    else if(boolean)//	#5
    		...code...
    	}
    	else//What if does this else go with?
    	    ...code...
    
    Well, do you think it is legal...do you...well, it IS LEAGAL! This is why it is called nested else's. Which else's goes with which if's. The way I formatted the code makes it obviouse, which is why we programmers code like that. Easy to READ. But what if they had no tabs. How would you be able to tell which else goes with which if. It is simple, each else will go to the next closes if, only if it is not already taken by a closer else. Other wise, it will go to the next one. Study the above code untiil you understand how it works.
    	//Notice This
    	if(boolean)
    	    ...code...
    	else if(boolean)
    	    ...code...
    	if(boolean)
    	    ...code...
    	else
    	    if(boolean)
    		...code...
    	//Both of these mean the same thing.  White spaces are not inportant.
    	if			(boolean)   {...code...}		else	if(boolean) {...code...}
    	//This is a legal expression, but as you can also see, very hard to understand.  Not recomended, at ALL.
    	//Please Don't DO THIS.
    	//If fact, your entire program can be in ONE LINE!!!!!!
    
    Looping:
    Repeating the same code over a number of times. You do this when you are want to do the same thing over and over again. For example, if you wanted to print out 'Hello World" 1000 times, it is very tedious to write the same code over and over again. It is easier to just write it once and tell the computer to repaet it a certain number of times. Example of Looping in C++:
    	for(int i=0;i<10;i++)//Setting the initial value for the incrementor, the condition that must be met in order
    			     //For the Loop to continue, and incrementing the loop counter.
    	{
    	    cout << "Hello World" << endl;//The statement that will be repeated a number of times.
    	}
    
    Examine the code and see if you can tell how it works.
    There are several types of loops: The For Loop, While Loop, and Do While Loop. Technically, they are all the same. You really don't need more than one, like the switch statement, it just makes it slightly simpler in some cases to choose one over another, but you don't to. In fact, I really just use the For Loop. In very rare cases do I use the while loop, and I NEVER used the do while loop.
    The difference between each loop simple, the while loop has the following syntax:
    	while(boolean)//Loop goes if boolean is true, terminates when it is false.
    	{
    	    ...code...
    	    ...some sort of incrementor that will eventually end the loop...//Otherwise the loop will never end, of wourse you have to
    									   //set an initial value somewheer outside this loop
    	}
    	/**************/
    	int i=0
    	while(i < 10)//When i is greater than or equal to 10, exit the loop.
    	{
    	     cout << "Hello World" << endl;
    	     i = i + 1;//This code is used very often, so the creators of C++ created a short way to represent this: i++;
    		       //Notice this and the language name: C++.  That name was derived with that.
    		       //C++ is 1 level higher than the original C, so C + 1 or C = C + 1 or C++!!!	:-)
    	}
    
    The Syntax for the For Loop:
    	for(initial value;boolean;incrementor)
    	{
    	    ...Code...//In this loop, the incrementor code is put at the location above that reads incrementor.
    		      //The Condition is put in the field read boolean
    		      //The initial value, well, if you don't get it by now, you don't have the brain power to be a programmer
    	}
    	/*****************/
    	for(int i=0;i<10;i++)//All of these loops do the same thing, can you see what they do?
    	{
    	    cout << "Hello World" << endl;
    	}
    
    The for loop incorporates all the neccessary things into one line. Thus, is the most commonly used loop. I won't bother with the do loop, it is useless. the difference between it and the while is that the do loop executes code first, then checks the condition whereas the For and while loops check conditions before execution.
    It is possible to break out of a loop. What if you want to do a statement 1000 times as long as another condition is meant. example:
    	for(int i=0;i<1000;i++)
    	{
    	    if(...Some Value... is not stupid)
    		i = i + ...Some Value...
    	    else
    	    {
    		break;//This statement forces the loop to exit.
    	    }
    	}
    
    This code will keep looping until it hits 1000 or the condition in the if statement is false. In case you didn't read the above code, the statement to exit a loop is 'break'. This statement can be used to exit any loop.
    Methods/Function Calls:
    A Method/Function call takes you from one part of your program to another. Since by now, you should know that methods and functions are the same, I will call them functions only. You can think of a function like a function in math. You inout some kind of value, or values, and the function output some sort of value.