C++ is a very verbose programming language that can be used to write very powerful programs. Though what listed below is certinally now everything you can do with this language, the programmer can do a lot with what is
talked about. More will be added to this page as over time. If you can't find what your looking for try the miscellaneous pages, to see if you can find it there.
Explanation |
Code |
iostream
First, we will start with: "#include <iostream>" (example right). Although most teachers will tell you not to worry about it, I find that having even a
small amount of understanding is helpful. iostream is used mostly for Input/Output. What this allows the computer to do is
gather information from the user and store it inside of some type of Data Structure. The output part of it allows
the program to display information to the user graphically on the screen. This is usually plain text such as numbers, letters and
sentences. For more indepth information go to cplusplus.com
|
|
namespace std
As for the include namespace std; (pictured right). This allows you, the code
writer, to be able to group classes, functions, and Objects all under different modular code structures. In other words, this allows the program to be devided into different "sections"
making it both easier to read as well as to program. So, instead of all the code having to be in one area, it can be split up into multiple areas.
For more indepth infomation go to cplusplus.com
|
|
Variable Types
There are many types of variables such as: integer, double, short, long, chars, Strings, and Objects.
The ones we will mostly be dealing with for now are: integers (int) and doubles(double). Integers are whole numbers such as
1,2,3...etc. Doubles are numbers with decimals in them such as: 2.0001,2.568...etc. There is also a way to make it so that once you
assign a variable a value it keeps that value and is not allowed to be changed. These types of variables are called constants, and
are annotated to the computer by the header before the variable type const (known as constants). Integers and Doubles are pictured right.
|
|
How Variable Types Interact
The way in which variables react with eachother vary, depending upon how you put them together.
For example a Integer that is added, multaplied, or devided, by another Integer, will always end with a integer value. For example 2+2 will be the integer 4.
3 devided by 2 will be the integer value of 1. Doubles are the same. If you add 1.1 + 1.1 you get 2.2. If you multiply 2.2 by 2.2 then you
will get 4.84, and finally if you divide 2 by 3 then you get .66666 repating. Now if you take a Integer added or multplied by a double
then that integer is turned into a double, and thus the variable type must be able to hold the change. For example if you have int
someInt = 1; and you have double someDouble = 1.1; and you take these two and add them together, a double
variable is needed in order to hold the outcome, becuase 1 + 1.1 (a int + a double) = 2.1 (a double). There is also a type of variable called
a char that is used to represent a letter. Though there purpose is to represent a letter, you need to note that letters, in c++, are
represented by ASCII charcters, which means that every letter has a corrosponding number, this means that they can not be easily compared
to other "Strings," which is a more advanced data type.
Go here see more examples and see further explanations on Variable Interactions. Examples of
chars will be shown later on.
|
Link for more infomation on: Variable Interactions
|
The "if" Statement
In programming you need to be able to make decisions based on what type of data
that you have at hand or what you want to do with the data. The most widely used method is the "if" statement, syntax
for the "if" statement is: if(condtion). "if" statements also come with another part to them, these are called
"else if" and "else." A "else if" allows you to place another condition inside of the "if" statement
and it looks like such: else if(condition). "else" requires no other condition, it really is just a fall back if all of the
other conditions fail (pictured Right). The common operators used inside of the "if" statement is: >=, <=, >, < and ==. Now you are
probably wondering why == is used instead of =. The reason this is used is because = is an assignment character that is used to give
a character a value, such as: int x = 2; The == symbol is a comparison function that checks to see if two values are equal to
eachother. Now this check function works best with intergers, for the reason of the binary system that the computer runs on, also
known as a "base two counting system" 0 and 1, we use a "base ten counting system 0-9. So, what does this mean? It means that the computer
has a dificulat time calculating decimal (double) values, there will always be a small error. In order to overcome this problem with doubles
it is best to stick with >, <, >= or <=. You will also be using the logical operators && (and), ! (not),
and || (or). Note also that you do not have to have a test value for the else, nor do you always have to have
a else with a if. Also note that if the code with the if statement is no longer than one
line, that is there is only one semicolon, that you do not need curly braces ({}), but if the statement
is longer than one line, or the equivalence of one semi colon the it is required that you have the culrly braces ({}).
Go here see more examples and see further explanations on "if" Statements.
|
Link for more infomation on: "if" Statements
|
LOOPS
In progamming you may need to print data out over and over again to show changes in data.
This becomes very tedious if you had to use a cout every time you wanted to print something. In order to fix this we have loops.
Loops allow you to print data out many times over with only a few lines of code. There are a couple different kinds of loops: while, for,
and do-while. A while loop executes "While something is true," and is also known as a
"pre-test loop." The syntax for a while loop is, while(condition). A for loop is used when
you know how many times the loop needs to execute, for example if you want to print out a statement so many times. The syntax for a for loop is,
for(counting variable; condition; incrament counting variable). The final loop is the do-while loop
which is a Post-test loop, which means that the loop will execute at least once before the conditions are checked.
The syntax for the do-while loop is, do{code} while(condition); . Keep in mind that all of the operators that you can use in a if statement
you can use in a loop. There are also operations, or key words, that will allow you to break out of a loop entirely or just break out one iteration
of it if you wish. These key words are break, and continue. Break will take you completely out of the loop, while continue will
skip one iteration of the loop.
Go here see more examples and see further explanations on Loops.
|
Link for more infomation on: Loops
|
FUNCTIONS
Functions are used to group statements together so that they may be called repatedly and be given
different values in order to perform a certain task. They also help to make the code more efficient and readable (called Modularizing Code) since you will be able to preform that
task every time the function is called without having to rewrite the same code over and over again. Functions are very easy to write and call,
the syntax looks like this: return value type (ie int) function name (ie max) (<parameters>). The body is held within curly braces ({})
so that the computer knows what code belongs to the function. If the function has no return type then, you put void, this means
that nothing will be returned when the function is called. Functions are usually written above the main, but if you want to write them below the main then you have
to use what is called a Prototype. A Prototype defines the function without actually implamenting the function,
so, in other words, you give the function a name and its parameters and thats it. This allows the function to be defined later in the program.
When a Prtotype is used, then you are allowed to place the function below the main. Whenever you call a function, such as the one described above, it would look like this:
int larger = max(4,3); Now if, the function max did not return any type of value then it would look like this when called in the main: max(4,3); Functions can also be over loaded,
this means that the function has the same name, but can accept different parameters.
Go here see more examples and see further explanations on Functions.
|
Link for more infomation on: Functions
|
ADVANCED FUNCTION FEATURES
Functions are great if you want to send data to them and have a value returned, but what if you want to change the value of a variable
that already exists? Or make a variable visible to all functions in the program? Functions infact do allow you to do this in a few very simple ways. If you want to change the
actual variable then all you have to do is put the & symbole infront of the variable name on the top. Example: void increase(int amount, int &toBeIncreased). Variables are also known
as Local or global. Local variables are only visible inside of the function that they are defined in. While Global variables
are visible to all functions within the program. Global variables are often defined right below the include statements. Variables also have what is called Scope.
Scope is where a varible is variable is useable, that is, the specific area in which a variable can be used and seen by a loop, function, or the program itself.
A for loop is a good example of this. When you inetate the counter (ie int i=0;), that variable is only useable inside of that loop, and if you declare another variable
inside of the loop, then that varaible is only useable from where it was declared to where the for loop ends.
Functions also allow you to declare Static Local Variables. These static variables allow the function to hold
the current value of a variable though different function calls. For example, if you have a variable count that is used to keep track of how many times a function is called, then
you don't want the variable to reset everytime the function is called. To avoid this you declare it as static int count=0; which keeps the variable's current value
even after the function code is completed. So if count is increased by 1 everytime the function is called then on the next call count will equal one, on the second call count will equal
two and so on. Keep in mind that the static variable IS ONLY VISIBLE(a.k.a it's Scope) to the function in which it was declared in.
Finaly, what if you, the programmer, still wants a function to run even if the user dosen't enter any infomation or your program while
it is running dose dosen't have the correct infomation? Well you can add in what is called "Default Arguments." What Default Arguments allow
the programmer to "pre-set" values for parmeters in a function. In order to do this just add a equal sign after the parameter and place in the default number that you want it to
be. The header would look like this: void cirArea(double r=1). With this default value, if the user enters a value then it over writes the default, but if the user enters
nothing, then the default value is used. If you do not want to give one parameter a defulat value because eather you know it is value that is comming from another
part of the program that the user dose not affect, or you know it will have a value everytime, then these variables are declared just like a normal parameter would be.
The only catch is, any variables that do not have a defulat value need to be placed as the first parameters. For example:
void doSomething(int x, int y=2, int z=4). Remember that you are allowed to set the default values to whatever you want/need them to be.
Go here see more examples and see further explanations on Advanced Function Features.
|
Link for more infomation on: Advanced Function Features
|
Arrays
Arrays are used to store large amounts of data. It usually helps to think of it as a collection of variables of all the same type. As for declaring an array
it is very simple, it is a lot like declaring a new variable...it looks like this: variable type (i.e int) name of array{size of the array}; NOTE: You must make a constant
variable that holds the size of the array since the computer will not remember it for you and there is no other way to access it. Also Note, that the constant
variable holds the pixel size (i.e the first spot is equal to one), not the actual size held in the computer (i.e spot one is index zero). Giving arrays values to hold is also very easy
since all of the information in an array is held in indexes An index is like a page protector inside of a big binder, and each page protector can only hold
one piece of paper with a small amount of information on it, whether that be a number, letter, etc. Each page protector has a number on it starting at ZERO and ending at
the last page. The first page protector in the binder would be zero; the second page protector would be 1 and so on. With these page protectors you can add information easily and move
it around inside of the binder as well. To draw a parallel with the array, the array name is the "folder's" name, and the number that goes inside of the brackets ([]), that where the
page numbers go. For example, say you want to place the number "12" in the first page of the folder. Since zero corresponds with the first spot, all that needs to be done is to select
the spot in the array and set it equal to that value. It would look like this: someArray[0]=12;
Assigning value to an array in such a way, as described above, takes a lot of typing as well as a lot of lines of code in the program. C++ gives
you the ability to both declare the array and initialize it all in one line. The syntax looks like this: double someArray [4] = {2.3, 5.7, 2.34, 7.9}; Notice that you still define
the size of the array but are able to directly place the values inside of the array. This means that the value takes the index value in the order in which they
are added to the array. So this means that 2.3 is in index 0, and 5.7 is in index 1 and so on.
What if you want to print out or even change data in the array, or what if you want to change the spot in which a value lies in the array? Well this is
fairly simple to do, all it requires is a for loop. Why use a for loop? Because all the elements are the same in the array, and the size of the array is known, thus the for
loop is the best loop to use. For loops allow many different tasks to be performed on arrays, such as adding numbers to them, whether it is in consequential order, or if there are random numbers
being added to it. They can be used to print it out, as well as swap multiple indexes quickly for actions such as sorting the array.
Arrays can also be passed to functions just like any other variable in C++, with an exception. Unlike a normal variable that you pass to a function, arrays
are always passed by reference. This means that if anything is done to the array then this will change the actual array it's self and this could change data that you do not wish to be changed or
give outcomes that make no sense. The best way to make the array a constant variable when it is passed into the function. This way if any of the code tries to change the
information inside of the array then the compiler will show an error, thus keeping you from making the mistake. Returning an array is as simple as passing it to the function. Just make sure
that you have the correct data type (i.e double) to receive the array that is returned from the function. The code in the function would look like this: return someIntArray[]; And in the main
it would look like this: intArray[]=function(a1[],SIZE); In the main, intArray[], after the function is called, will be identical to someIntArray[].
Go here see more examples and see further explanations on Arrays.
Click on one of the links if you wish to learn more about SORTS or SEARCHING arrays.
|
Link for more infomation on: Arrays.
|
Objects and Classes
Though there was a lot learned above, that alone is not enough information to be able to program large complicated programs.
In order to produce large and redundant programs you need Object-oriented programming (OOP). OOP is programming with objects. Objects
represent entities in the real world such a student, circle, etc. Classes help you do this, classes use variables in
order define objects such as circles, and with the class you can retrieve, access, print out, and change any information you want. The way you define a class is:
class className (i.e circle). Then right below that there are curly braces ({}) and the last one is followed by a semicolon (; unlike functions).
Next you want to add inside whether or not the functions are public or private. At least for now, most of the time you are going
to make the class public. Pubic means that the variables and functions inside of the class are all visible by the rest of the program. While private
means that the variables below it can only be seen and used inside of the class. All you need to do in order to use public or private, just be inside of the curly
braces of the class and put: "public:" or "private:" and everything right below that will be either public or private. The next important part of a class is the
Constructor which allows you to inmate the class as well as sends it the initial information to start using it. Constructors have
three basic rules that need to follow: 1) The constructor is the same name as the class. 2) They have no return type, just there name. 3) They are involved
when the object is created; they play the role of initializing objects. Inside of that constructor you need to set the parameters that are passed to the
constructor to the global variables inside of the class so that you will be able to use them. There can also be multiple constructors, each one accepting different
parameters, a lot like a function. After you complete your constructor you can create your class functions, the same way you would create functions above you main,
except for they are inside of the curly braces of the class.
Once you have your class created it is very easy to call and use that class inside of the main. So for example, if the class is
called circle all you have to put is: class name (i.e Circle) what you call the class in the main (i.e circle1)(parameters); Calling class functions looks like this:
name of class in main (i.e circle1).class function name (i.e area)(parameters);
Go here see more examples and see further explanations on Objects and Classes.
This is in no way all you can do with classes, this is mearly a simple introduction to classes and how they can be used, and to help understand them a little better.
|
Link for more infomation on: Objects and Classes.
|
Multidimensional (2D) Arrays
Declaring a 2D array is just as easy as declaring a single dimensional array except now, instead of one field, there are multiple smaller
arrays inside of one array. In a sense a 2D array is an array of arrays, the syntax for declaring a 2D array looks like this: data type arrayName [# of rows][# of colums]
= [#'s],[#'s]; Declaring a 2D array is also pictured right. One way to remember which brackets should contain the rows and the columns is to think of RC Cola, R=row,
C=Colum. Just like a one dimensional array, you need to keep track of the size of it. The best way to do this is to make two constants, one that holds the rows and the other that holds
the columns. Assigning values to a 2D array looks like this: my2DArray[0][0]=1; Thus, in row 0, column 0, my2DArray now has the value of 1. More information will be provided on the example
pages.
Go here see more examples and see further explanations on Multidimesional Arrays.
|
Link for more infomation on: Multidimesional Arrays
|
The String Class
The String Class allows the user to do many different tasks with string literals and C-strings. The best way to think of Strings is to think of them as
an Array of characters with what is called a "null terminator ('\0')." This tells the computer that this is the end of the of the C-string and to stop at that location in the Array.
It is very easy to declare an empty string, much like declaring a empty int or double just put: string s1; C++ uses the no-arg constructor (no argument) to make an empty string. The programmer may then
use the the class function: string message('string literal'); Inside of the () you can place a word or sentence. The programmer may also assign a word or sentece to the string
by simply putting: s1="what the user wants"; The programmer may also Append to strings, whether it be in the middle of the already created string, end of
the string or even the beginning. The programmer may also want to print out or grab a specific letter out of string litteral. The programmer can use the
stringVarName.at(index); *Note that the first letter of the word/sentence will be index 0. The programmer may also get the size, capacity, and c_str()
of a string. Their are many other functions the programmer can preform on strings, they are all listed on the explanation page.
The string class has string operators that can be used to compare and edit string variables. Their is the equal sign (=) which allows
the programmer to assgin a string to a string variable. The plus sign (+) will allow the programmer to add to a string, they may also
use the plus equal (+=) to add to a string variable. The programmer may also use the brackets ([]) to access a char
at a specific index. << allows the programmer to place a string into a stream, such as the output stream, and can use >>
to extract a string from the stream, such as when a user inputs their name. The string class also allows the programmer to compare strings the same way
as comparing intergers. I personally was taught not to use these, but they are: ==, !=, <, <=, >= , and >.
Go here see more examples and see further explanations on the String Class.
|
Link for more infomation on: String Class
|
Logic Charts and UMLs
Logic charts are one of the most important skills you need to be able to write effective programs. To make a logic chart you will first need to break the problem down into
steps. For example, as pictured right, you know that you want to initialize the program, read in the first word, process the word, print the word to a new file, then clean up the program. Now you want to use
step wise refinement to break each of the large chunks into smaller chunks. For this program we want to check if each word is a is a palindrome. There would be a lot more to this chart if the program was more
complicated. As you can see, we are not writing any code, just putting our logic on paper. The first level is called our level level one Algerthm, this is what should apear in main. Everything
else below should be functions, such as checkword.
Now we are going to talk about UMLs, or Unified Modeling Language. These charts help the programmer decide what setters, getters, and variables he/she needs
inside of a class. A UML is pictured bottom right. In this simple example we are going to make a UML for a class called Rectangle. When you see a - sign that means private, only the class can
see this variable. If you see a + sign, it means that the class and any other program can see it. Whenever you see a : and then a word such as double or void, this is the return
type. Where you see Rectangle() in the middle, this is the constructor, as you know it has to have the same name as the class. In this case we have two constructors one that has no parameters passed
to it and another that is passed a width and a height. Finally, if you see words inside of ()s this means that it is accepting parameters. Again this is a very powerful tool to have when programming,
especially when working with Classes.
|
|
Pointers
Points are the heart and soul of C++, they allow you to use dynamic memory, that can greatly improve the effectiveness of your programs.
With pointers though you have to be very careful with what you are doing with them. For example, if you delete a pointer and you delete the pointer, but not the data it is
pointing to, you then have what is called a MEMORY LEAK. Although the OSs garbage collection should handle the bits that are left over, there is a possibility
that it won't and could do serious damage to the computer, or even cause another one of your programs to do something you really don't want it to do. A golden rule is, if your done
with the memory the pointer is pointing at erase DELETE that section of memory. You also have to use the BIG 3, shown on linked page, that you must include in
your class if you use dynamic memory. There is too much detail to go into on this page, so please refer to the
Pointers pages.
|
Link for more information on: Pointers
|
File I/O
You have used basic input and output using the >> and <<h;. There are functions that you may also use, such as
getline, get, and put. With getline, you can choose the deliminator, with get(), you can decide what to do with each character in the file, and put you can
place a char of your choice to the file. Examples of these will be placed on the example page.
fstream
fstream gets a section of it's own because it is very different from what most people are use to. For example in ifstream and ofstream you
were able to include them and read or write to a file with doing little more than giving the file name. With fstream not only does the programmer have to provide
the file name, but he/she also has to tell it, whether the file is being written to, read from, exists or not, if its text or binary, or to append to it or just over write it.
There are also many other tests that you are able to perform, in addition to the fail() and eof() tests. Listed on the example page.
|
Link for more information on: File I/O
|
Operator Overloading
Operator Overloading allows the programmer to tell the program what he/she wants it to do in a specific situation. For example, you can define
how the + sign will affect your class. So lets say your class has a list of items in it, you could the + sign all all the values of both lists to a new list
and return the new list inside of a class, complicated right? I'll show more examples on the following page, Operator Overloading.
|
Link for more infomation on: Operator Overloading
|
|