Sie sind auf Seite 1von 22

Thank you for downloading this tutorial.

I am glad that you chose this tutorial


among all the ones out there. You may like it, you may also not like it. But ple
ase vote on it at
www.1cplusplusstreet.com because I spent alot of work, time, thinking, solving,
remembering, and deleting and rewriting to make this tutorial as simple, efficie
nt,
understandable, and able to make you succeed as possible.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------PRE LESSONS: Complete Introduction
~
C++ is, like I said, a complicated language. If you can learn C++, you can learn
nearly any other computer language easily. But you need to focus. The estimated
time
that you will probably finish, understand, and be independant on what is taught
on this lesson is, in my judgements, 1 and a half months. There is always the sh
ortcut, which
is what I did when I was learning. That's where you learn a little, and through
playing around, viewing other's source code, and just seeing code you expand you
r knowledge.
But to start, we will use the normal way of learning:through lessons and interac
ting. But to start, we need to make sure about a few things:
First off, you need a compiler. You can go out and buy one, but don't unless you
really want more than just compiling and getting things done. For now, use a fr
ee one.
Here are a few FREE compilers!:
Digital Mars compiler (the one I use!) www.digitalmars.com
Dev C++ www.bloodshed.net
//ANSI standard. See ANSI tutorial file for detai
ls
Borland compilers www.borland.com
Download.com (search for "C++ compiler") www.download.com
Most are just quick to download an compile fast. Digital Mars has one of the fas
test compile times recorded, so start there if you want. Any you find will do, l
isted here or not.
Next, I have included examples for each chapter, or lesson, in the Examples fold
er you should have recieved with this tutorial. Study them and use it in combina
tion with this
tutorial. To start off, I should talk about file endings. You know, the prefixes
in program names that state the type, like ".txt" or ".mov". When you write a C
++ file, you must
use ".cpp" or else the compiler might give an error. There are varieties, but th
at is most common. A few varieties are: .cc, .cp, and despite this being for C f
iles, some still
use ".c". So remember to add one of those prefixes to text files of C++.
Ready? Let's start!
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson1: Hello world!

~
Nearly every programming language tutorial starts with a "Hello World" program.
Well, lets start with that, but explain it completely.
#include <iostream.h>
int main()
{
cout<<"Hello, World!\n";
}
Compile the above program and congratulations! You're a C++ Programmer!!
!! You've made and compiled your first program!!!
Now, lets examine this program:
Line 1:#include <iostream.h>
"#include" tells the compiler to take the file "iostream.h" and make the functio
ns in it ready for use. Anything in C++ that starts with
"#"(pound symbol) is called a "preprocessor directive". What is a preprocessor d
irective, you ask? First off, the preprocessor is a
thing the compiler does before reading the code.
Now, you might know what iostream.h does, but if you don't, it defines all the f
unctions required for input/output. You see "cout"? That
is one of them. "cout" is what you type to tell the compiler that everthing foll
owing the "<<" is to be printed to the screen. The "<<" is
there to take everthing following it and do the "cout" function on it. It is req
uired for cout to work correctly. The "<<" are directives
telling that take the following information and do all the functions of cout on
it.
Line 2:(blank)
In C++, spaces and returns are not required. You can take out the spaces and ret
urns in this program and it will run correctly. But, you
can't take out all the spaces and returns. You need them for certain things. Her
e is a very brief list:
*Spaces must be between a variable name and the data type (we'll talk about thos
e a little later)
*A return must be after any preprocessor directive (again, we'll talk about that
later on)
*The "no spaces/returns" rule does NOT count for quotes. You type things in quot
es exactly how you would write it on paper.
And many more will be covered as we go on. If you feel confused now, don't worry
. I will cover everything I talked about so you know
and understand everthing.
Line 3:int main()
This probably looks confusing if you know nothing of C++, so let me explain. "ma
in" is a *required* function in every program. If you
don't have it in your programs, the compiler will have an error and it won't com
pile. That is because "main" starts the program's
operations. It can be anywhere in your program, but it must be there. Think of i
t as the script of the program, in that it has the order
and rules to run the program. If you have multiple functions, you call them all
from main in the order that you want them to happen. For
example, here is a program with 2 functions, but main calls the second function:

#include <iostream.h>
void multiply();
//If there are multiple functions other than main(),
you MUST declare them at the beginning of the program
int main()
{
cout<<"An example of multi function programs!\n";
multiply();
}
void multiply()
{
cout<<"2*2=4";
}
You see how important main() is? "multiply" would never happen if it is never ca
lled, so since no other function is calling it, main() calls
it and it does the contents of "multiply()". Now about the "int": "int" means t
hat the function has a return. You can also use void, but this is not ANSI stand
ard,
so you may not use void with main(), because main returns 0, ending the program.
There is a line in C++ that tells the compiler when the program has stoped and
finished. It is NOT required, but it won't hurt to add it. It is written as "ret
urn 0;". Thats the return that I am talking about. The "0" means
that the program has finished executing, and the application ends. The applicati
on is still open, but there is no more commands to do.
Most ANSI compilers, like Dev C++, put the line in by itself, so that is why it
is not required. We'll talk more about "int" a little later on.
But for now, thats how it works. The parentheses are used with nearly every call
in C++, and they are there to tell the program what variables
to carry with it. The stuff that goes in the parantheses are called "arguments".
You shouldn't worry, as they are really just for more advanced
C++.
Line 4: {
This is what you write to say that the function is going to execute. It starts t
he function, and it starts executing until the end bracket is
reached.
Line 5:cout<<"Hello, World!\n";
As described above, "cout<<" is how you output something to the screen. Everythi
ng after the "<<" is printed to the screen. So here,
the quotes are taken out, as they just hold the text to print, and Hello, World!
is printed to the screen exactly like that. Now, what about
the "\n"? "\n" is one of the "escape commands", or a command that does something
simple to the text. In this one, "\n" is used to tell
the program to skip to the next line and continue from there. The "\n" is not pr
inted, as anything that starts with "\" in quotes is considered
an escape command. Here is a list of alot of them:
\n --Skips to the next line and continues from there
\t --Does what the "tab" button does. It indents about 3 space
s.
\\ --It prints a "\" to the screen
\' --It prints a single quote to the screen
\" --Prints a double quote to the screen
This is all that will be used often by you. Memorize it because it is used quite

often. Finally, that ";". That is used whenever a single


command is executed. Here, the text has been printed so we put that there to tel
l the compiler that command has finished. It is required.
Line 6: }
Ending bracket. It ends the function.
There! You have completed the introduction to the world of C++! Feel proud beca
use you are one step closer to becoming a great programmer!
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 2:Include files
~
Include files are files written in C++ that define functions, variables, and man
y other things so you can use them to execute things that are included, or
used along with, your C++ source code. iostream.h is an example. All include fi
les end in ".h" and are included by typing "#include <includefile>".
Replace "includefile" with the name of the file, of course. Now, you might be wo
ndering, "How does the compiler know where the file is?".
It knows because of a simple rule:
If the file
you put the
If the file
e between 2

is in the default directory the compiler has set for include files,
file name between "<" and ">", like <iostream.h>.
is in the directory that the source code is in, you put the file nam
double quotes, like "iostream.h".

Really the only time quotes are ever used for including files is if you created
a new include file in the same directory and need to use it. Otherwise
everything you need is in the compiler's directory and just use the "<" and ">".
All the include files in this tutorial use < and >.
Understand? Good, because lets continue! Now, a good rule to remember is that in
clude files are not named that all the time. Sometimes they are
called "header files". We'll call them either from now on. C++ is nearly useless
without header files, because most of the definitions to communicate and
do advanced things are in several header files. So how do programmers learn all
about every header file? Well, in school the important ones are taught and used.
Also some people, like me, look through the files for things they need. Usually,
header files come with comments in them describing functions of some variables.
Otherwise, the developer figures it out based on statements around it and the va
riable name. I will tell you about different functions in include files as we go
on.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 3:Variables
~
Variables are names of memory slots that store information based on the data typ
e. Example:I could define "bigNumber" as a variable to store
numbers. Think of variables as dogs. Say you have a dalmation that is named Spot
. In C++, this would be written as "dalmation Spot;". The
data type is dalmation, and the variable name is Spot. Variables are easy to und
erstand as they relate to the real life system of naming objects.
A variable name could be anything, but it can't be any reserved words (words tha

t are C++ words, like "void"), must start with a letter,


can't have spaces, and only letters, digits, and an underscore ( _ ) may be used
. Try to avoid unecessary words in the variable name,
like "bigfatlongconfusingnumber" or unprofessional names like "something". Now,
all variables are used differently based on the type they are.
Here are basic variable types and their abilities of storing what type of inform
ation:
char
--Stores 1 letter, number 0-9, or punctuation symbol
~char stands for character
int
--Stores 1 number from -32768 to 32767
~int stands
for integer
long int --Stores 1 number from -2147483647 to 2147483646
~lo
ng int stands for long integer
unsigned int --Stores 1 number from 0 to 65535
unsigned long int --Stores 1 number from 0 to 4294967295
float
--any 1 number with a decimal point
const --Put in front of any data type to make the variable non
changeable, as in you have to give it a value and you can never change that valu
e after.
bool --Let's the variable return/store "true" or "false" (0 or 1
). **In older compilers, you must include bool.h to use this data type
So if I wanted the user to type in one letter, I could make a new variable to st
ore the input like this:
char input;
In C++, you can have multiple variables on one line. Of course, they all have to
be the same type and are separated by commas. Example of multiple variables on
one line:
int a, b, c=2, d;
Now, how do get the input to the variable? Easy! You use a function from iostre
am.h called "cin". It collects input from the user and stores what
it can in a variable like the following:
char input;
cout<<"Enter 1 letter: ";
cin>>input;
//the ">>" means to take cin and perform the functions on "inp
ut". These are comments and will be talked about later.
It is just like cout, except it goes the other way.
*Remember: cout goes with "<<", and cin goes with ">>"
Now for the part of assigning values to the variables. You may only assign value
s to variables that the data type can store. If you store more than it can hold,
it will cut off
the excess data and only store what it can. For example, if I ask the user to i
nput 1 letter to a char type variable, but the user inputs 3 letters, only the f
irst one will be
stored. A workaround for this is to do "multiple inputing", as I call it. "Mult
iple inputing" is where we define multiple variables and use them in one cin>> f
unction. For example, if you want 3 letters inputed, you can define 3 char's and
use them in the cin>> function asking the user for 3 variables.
Example 2.1-Multiple Inputing:

#include <iostream.h>
int main()
{
char in1, in2, in3;
cout<<"Enter 3 letters: ";
cin>>in1>>in2>>in3;
cout<<"\nThe letters you have inputed are "<<in1<<in2<<i
n3<<" .\n";
}
Another very important rule is to save as much memory as possible. If you use a
data type alot of times in a program just to get the same type of input, define
the
variable at the beginning of the program. If you define it at the beginning of t
he program, the defining part must stay out of functions to make it global, or u
sable in any
function without multiple definitions. Heres an example of "global defining", or
defining variables at the beginning of the program for use in any function with
out redefining it:
#include <iostream.h>
char input; //I defined it before any functions are called, and I can now use
it in every function without having to redefine it
The reason to do this is to save memory. Say I create a calculator program and w
ill constantly be using an int data type variable to get input. Instead of call
ing it over and
over again taking up memory, I can define it like above and be able to use it an
ytime without redefining it. What if I already used it and it is storing someth
ing? Simple-it gets deleted and replaced with the new input. Like if it is crea
ted as a global variable and I use it to get info in the function "void getInput
()" but then use it to get input in the function "void getMore()", the input fro
m "void getInput()" is erased and the new input from getMore() is stored.
**IMPORTANT:To use global variables, you MUST declare them at the beginning of t
he program. Otherwise they won't be global. Also, if there are multiple functio
ns in a
program, you MUST declare them at the beginning as well. For example, if I had a
nother function in addition to main(), I would have to declare them at the top l
ike this:
#include <iostream.h>
void anotherFunction();
That is required for functions other than main(). The function definition is cal
led a "prototype".
Homework:
Create a program that gets 3 long ints from the user. Then add them together in
side a cout<< line using the "+" sign to add. The answer is in the Ch. 3 example
s folder
included inside the main Examples folder.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 4:Producing Grea

t software
~
C++ can do a truckload of things. It can calculate things easily and quickly eve
n a human gets confused by, store multiple inputs, keep histories of usages, cre
ate files, and
a motherload of things. But when you learn C++, and basically any language, you
will begin to understand why creating programs that are extremely useful is the
goal of
learning a computer language. It can be useful for your own use, or you can make
it useful for a huge company. Some examples of programs that make the world sta
y
accurate and updated are:
*Banking software
*Satelite systems
*Virus protection
*System software
*ATM machines
*Stock market
*Anything that is stored or relies on computers
See how important programs are? That's why so many people learn computer languag
es. They want to be part of those software needs. But what if alot of those prog
rams
didn't work or had to many needs to run? That's what this lesson, or should I sa
y explanation, is about. When you learn C++ and any computer language, you are l
earning
how to run the very maching you are using to read this. You can now customize th
e computer to do what you want, instead of relieing on companys to do it for you
. But, to
make your software needed and useful, you must follow 3 simple steps: Easy to us
e, as independent as possible, and as useful as possible. A good example of this
is the
system software you are using right now. It is easy to understand, gives you alo
t of resources to use for your own uses, doesn't require much more than a proper
computer,
and is required to run anything. A bad example is a program that crashes often,
takes up alot of resources, is based solely on you knowing what it wants, and re
quires alot
of things. Remember this line: Easyness sells. You wouldn't buy a program that d
oesn't give you an easy interface and requires alot of thinking. So when you mak
e your
programs, you should try to make them as good as possible. You want people to us
e your software. People won't use it if it performs poorly. Of course, every pro
grammer
has fun with programming. Some people create programs for entertainment, and som
e create programs that do nothing but are made simple to pass time. I have inclu
ded
2 examples, one that is a bad example of software, and one that is a good exampl
e of software, in the Ch. 4 example folder inside the main Example folder.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 5:Comments
~
Comments are in about every programming language. They are there to add a commen
t about whats going on in the code. The compiler ignores them. In C++, there a
re

2 different styles of comments: one from C, and one that is new. Here they are:
/* <----Start of C style comments|End of C style comments----> */
// <---------Start of C++ style comments. This type ends the line and t
he rest of the line is considered a comment
Is there a difference between them? Yes. The C style is able to be put in the mi
ddle of any line and close them up to continue with the code. The C++ style ends
the line
completely and you must skip to the next line to continue with the code. Here ar
e two examples of each style:
int main() //These are C++ style comments. I must skip to the next li
ne to start main(). This line has ended.
~
int main(/*Comment*/) /*These are C style comments. You see how I put a
comment in between the parentheses? I can because they are closable.*/
See the difference? They are intechangeable, so you can use either style anytime
. But the C style MUST be closed with */ . If you open the comment up but don't
close
it, the rest of the code is considered comments. Now, people like doing neat thi
ngs with comments. I personally I seen tons of source code, and nearly all of th
em had
"comment special effects". It is optional and programmer puts them there just f
or decoration. Here are 3 examples:
/*
*This is one style of comment side effects.
*I call these "rope style" because it looks a rope of stars.
*Call them whatever you want. Looks cool, huh?
*/
/****************Here is one liner effects. These are preferably for one
line comments, but you can use them on multiple lines.*******************/
/****I call these "Apple comments" because I used to program Macintoshes
and frequently saw Apple coding. Alot of them had this style.********/
/****The style here is that the comment line ends and starts again on th
e next, each time closing it and reopening on the next line. See--------->*/
They, again, are optional and are used simply for decoration. Get creative. You
can do anything in the comments because the compiler simply ignores them and sk
ips over them. You just need to open and close (C style) correctly and no worrys
. But the thing to using comments is that you must try to keep it quick and simp
le. If you get coding from big
companies, they will usually include a copyright notice, disclaimer, and sometim
es edit history. They don't include comments just there for enjoyment and have n
othing to do with the code. Don't use comments to include things other than nece
ssary things or things that will aid in understanding the code.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 6:Math operators
~
In C++, math is a very rich and large section. C++ can do just about anything in
math. It can find square roots, do scientific caculator commands, find remainde
rs, use

decimals, and more. Most of the symbols are the same, except for 3: multiplicat
ion, division, and modulus. Modulus is a method that finds the remainder of num
bers.
The symbols used are:
* =multiply Ex. 8*2=16 (thats an asterisk. Press shift-8 to write)
/ =divison
Ex. 8/2=4
% =modulus Ex. 8%3=2
Most of the more complicated functions, like square roots, are found in math.h.
Here is a list of just a few of the functions in math.h:
FUNCTION:

MATH.H BRIEF LIST OF FUNCTIONS


DESCRIPTION:
HOW IT L

OOKS (IN C++


tan(double x) --Finds the tangent of an angle-------------------tan(variable); -OR- tan(3.14) <---Numbers MUST be in radiants
if using real numbers
sin(double x) --Finds the sine of an angle-------------------------sin(variable);
sqrt(double x) --Finds the square root of any nu
mber------------sqrt(variable); -OR- sqrt(56);
cos(double x) --Finds the cosine of any angle------------------------cos(variable);
pow(double x, double y) --Multiplies x to the po
wer of y---------pow(variable,variable) -OR- pow(45, 3)
abs(int x)*
--Finds the absoulute value of any numb
er data type----abs(variable) -OR- abs(-90)
*for some reason, abs() is sometimes included in stdlib.
h . Check your compiler's include files.
You don't necesarilly need the above to do those functions. Like to make a homeb
rew of abs(); you can use if() statements, which will be covered later on in thi
s tutorial. Get
creative with math in C++ because it is wide and is extremely smart at figuring
math out. In C++ math, there are twists to the normal equal sign ("="). Here is
a table about
what I mean:
Symbol:
|
What it means:
<=
| Less than or equal to. Usually comparing a variable to either an
other variable or a real number.
=>
| Greater than or equal to. Again, usually comparing a variable to
either another variable or a real number.
==
| Is equal to. This is different than the single "=" sign because
it takes a variable and sees if it is the same as the following *without* changi
ng the variable's value
Ex. if(variableName==5)
//Checks if variableName is equal to
5 *without* changing variableName's value to 5.
!=
| Is NOT equal to. Same as the 2 equal signs except negatory (tha
t's an exclamation mark in front of a equal sign)
||
| "or". Used in if() statements (covered later) or any test statemen
t. It is written by holding shift and pressing the button above "return" twice.
&&
| "and". Used, again, in if() statements and any testing statement
s.
|
| Used simply to tell the compiler to go to the next line and co
ntinue from there if you press return when putting things in a function's argume
nts, or parentheses.
Ex. function(int a, char b, long int c, |
bool d)

()
| In math statements, whatever math operation is in the parentheses
gets solved first and then everything else. If there are multi "()"'s, then it g
oes right to left order.
<
| Less than. Used mostly in math statements, but a few times in functi
ons.
>
| Greater than. See description for <.
Use these when needed. They all can be used in math, but some, especially the la
st 4, can be used in anything, like testing statements (see next chapter).
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 7:For, while, and do loop
s
~
In C++, there are functions that start a loop of events. Just like in real life,
we have the process of loops. We eat breakfast, lunch, and dinner in a constant
loop everyday.
That's what C++ is like. Except that it has 3 types of standard loops. They are
used differently, but create the same effect: a loop. First, we'll talk about a
"for" loop.
6.A: For loops
~
"for" loops are loops that use variables to declare the starting point and endin
g point, or when the loop will stop looping and happening. To use a "for" loop,
you need to make an integer. There are probably different ways to use variables
in a for loop, but for now we will start off with a simple integer variable rese
rved only for our "for" loop. So, define your integer variable in the function y
ou will use it. It can be called anything (remeber good variable naming etiquett
e). Now, I will create a model of a "for" loop. You will probably not understand
most, if not all, of it, but that's alright. I will go over it. Here's the mode
l:
What the variable's currently equal to (defaultly 0) | The variable needs to rea
ch 10 to stop
/ | \
/
| \
for(variableName=0;variableName<=10;variableName++)
\ | /
Add 1 to the variable
every completed loop
{
~loop contents~
}
Confused? Don't worry, I am now explaining it. We first start off with the word
"for", obviously saying it's a for loop. We then add the parentheses as with an
y function and
include all the contents and "schematics" of the loop. variableName is the varia
ble that I told you to define. I just called it that for teaching purposes, so r
eplace it with your
variable's name. Since the variable's declaration didn't include what it contain
s or is equal to, it is defaultly set to 0 (zero). So right in that spot you pla
ce what the
variable is currently equal to. It is best to always have a variable equal to 0
when you start, but it really depends on what you want to accomplish with the lo

op. For now, it's


equal to zero. We then add a semicolon (";") to end that part of the function. N
ext, we tell it what the variable needs to reach to stop. Why is there a less th
an sign? Because
if the less than sign wasn't there, the for loop would get confused because it s
eems as if it's receiving two values at once and it would give an error. You can
also put a
greater than sign, but either way it is as if the greater/less than sign isn't t
here. So, once the variable reaches the given amount, or in this case 10, it sto
ps the loop. That
means that it will loop 10 times and stop. So how does it reach that? Easy-it's
in the next part. The next part shows the variable name and 2 plus signs. The 2
plus signs
mean to add 1 to the variable every time the loop completes one time. That's how
the variable makes it to 10, or whatever the ending number is. After that, you
add braces
and start the loop. You put the loop's contents in between the braces. It can d
o anything, just like as if you were coding without the loop. Now, about the 2 p
lus signs. In
C++, the 2 plus signs mean to add 1 to a variable. But the place that the 2 plus
signs are in makes a difference. If the ++ is at the end of the variable name,
something
must be completed to add 1 to the variable. Like if you want to add 1 to the var
iable after you print it's current contents, you would add ++ to the end. Exampl
e:
int variableName=5;
cout<<variableName++;
//It prints 5, the variable'
s current value, and after it prints it, it adds 1
But if the ++ is at the beginning of the variable, it adds 1 to it before anythi
ng else happens. It is exactly the opposite of the one with the ++ at the end.
6.B: Do loops
~
Do loops are loops that will happen at least once, and then test a variable to s
ee if it should continue looping or not. Do loops are somewhat like for loops, b
ut not too much.
To set up a do loop, you again need an int variable. Here is a model of the "do"
loop:
Name of loop and an opening brace following
|
do{
~loop contents~ <----Contents of the loop
}while(variableName=1);
\_____|______/
|
Telling it to continue doing the loop as long as variableName=1
First, we open up and start the loop by putting "do" followed by an opening brac
e. Now, the loop is going to happen at least once until we get to the "while()"
statement.
Next, we put in the loop contents, followed by a closing brace. Next, we put the
while() statement, which will make the loop keep happening as long as the varia
ble is equal
to a certain amount. In the example, it will keep happening as long as it is equ
al to 1. Then after that, we put a semicolon to end the loop. Remember, you must
remember
that in a do loop, the loop completes once and then goes to the while() statemen

t and then sees if it should continue. A "for" loop doesn't happen unless the va
riable test is
true.
6.C: While loops
~
While loops are extremely simple. So simple that in fact this part of the tutori
al will go extremely quick. To use while loops, you again have to have a variabl
e to test. For
the example, we will use an integer called "tester" (it's so simple that a model
is not necessary). We start the loop by typing our old friend while(). Then in
the arguments,
or parentheses, we put, "tester=1". Of course, since nothing happened to give te
ster an accumulated value, we gave it the value of 1 when we assigned it. So the
loop
does look like this so far:
while(tester=1)
Next, you put an opening brace, put the contents of the loop, and then close it.
There! You're done! See how easy a while() loop is? But now you may wonder, "If
it's that
easy, why don't I always use that loop?". Because, this loop is also very simple
. It doesn't have the features of, say, a for() loop in which you can only make
it happen a
number of times before it stops. It doesn't happen once and then test to see if
it can continue like a do{} loop can. It also doesn't have tricks like a for() l
oop has, like how
for() loops can make a delay happen by counting to extremely high numbers multip
le times by putting a for loop inside a for loop. Other than that, you are free
to use any
loop based on how and what you will use it for.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 8:if() and else()statemen
t
~
In C++, there comes a time in which the program has to make decisions based on w
hat is currently happening. It is just like in real life. That is what the if()
statement is for.
It pretty much explains itself, so this will be a quick lesson. Let's start. As
with any function, it needs parentheses. In those parentheses we put the data to
test. Maybe you
need to see if a variable is equal to something and work differently if it is. W
hatever it is, it follows a basic skeleton:
if(variable==something)
{
~what to do if it is true~
}
Really, the only thing you
riable. After that, we put
he variable equals
the following. Most of the
ctually, I think it always
ts between the braces

would be testing would be a variable. So we used a va


our good old friend-the double equal sign-to see it t
time it will be either a letter, string, or number. A
is like that. Anyway, if the test is true, the conten

will be performed. As with any test function, it could be anything. We then clos
e the braces. But what if the test is false? That's when the helper function els
e() comes in.
Else tells the program what to do if the previous if() statement is false. If yo
u have more if() tests to do, you would write else before the following if()'s.
If you have no more
tests to do and have something for the program to do, you write else by itself f
ollowed by braces. In the braces, you tell it what to do. Here's an example:
if(variable==70)
{
cout<<"\"Variable\" equals 70!";
}
else if(variable==50)
{
cout<<"\"Variable\" equals 50!";
}
else
{
cout<<"\"Variable\" does not equal 50 or
70.";
}
Understand? Good!
Homework:
Write a program that gets an integer from the user. Then test if the integer is
greater than 50 but less than 100. If it is, tell the user that. If it isn't, te
st if it is over 100 but less
than 200. If it is, tell that to the user. If none of the past two are true, tel
l the user that.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 9: Reference Variables
~
In C++, there comes a time where you need variables in a certain function that a
re defined in a different function. Like if I made a function called addition()
and it needed
to use input from main. Well, in C++ doing that is a little complicated, but eas
y enough to learn if you pay good attention. The only time you will ever need th
is is if you are
using multiple functions. To start, make a new C++ file and declare the second v
oid function's prototype at the top of the program and call it "multiply", but i
nstead of having
nothing in the parentheses, put the words "int &input, int &input2". See the "&
" in front of the integers? That means that those integers will not be used to s
tore data
originally for them, but to act as "dummy variables" or to be variables that can
be replaced with any variable name assigned to it, and also to get data from a
different variable
from a different function *and* both the function that called the second functio
n and the second function both get
affected by the changes. If there is *no* "&" in front of the variables in the a
rguments, or parentheses, of the function, then only the function changing the v
ariables' values

gets affected. Because of that reason, the names in the arguments of the second
function can be replaced with any variable names from the same data type. Here i
s an
example of the confusing reason I just gave you:
void multiply(int &someNumber); /* This means
that the function calling this and this actual function get affected by any
changes to the passed on variables, regardless of which function the changes hap
pen
in. */
~
void multiply(int someNumber); /* Having no "&"
sign makes only this function affected by any changes to the passed on
variable that are made in this function. So if main() shares the same variable(s
) that get passed on to
this variable, only this function will be affected by any changes made in this f
unction. */
when it will be used. Next, start main(). In main(), declare two int variables.
You may call them anything, but I will call the first one "multiplyOne", and for
the second one, I
will call it,"multiplyTwo". Next, ask the user for 2 numbers, either by using bo
th variables on one "cin>>" line or 2 different "cout<<" and "cin>>"s. Now, here
is the part where the second function happens. Write the line, "multiply(multip
ly, multiplyTwo);". Remember when I said that the variable names in the function
prototype can be replaced with any variable as long as it is the same data type
? Well, that's what we just did. We called the function, just like how we assign
values to variables, with the 2 variables used. Now the function will use those
variables when it does the commands it is coded to do. But it is only able to d
o that because of the "&" we put in front of the variables inside the parenthese
s, or "arguments", in the second function's prototype. Now, close up main() to s
tart the second function. Start the second function with the name from the proto
type, you know, "void multiply(int &input, int &input2)", and put an opening bra
ce. Next declare an integer called "answer". This will hold the answer to the mu
ltiplication we will do with the passed on variables. After that, you pretend th
at we are still using the dummy variables, in this case "input" and "input2", by
assigning the answer variable's value to input*input2. But remember: we assigne
d multiplyOne and multiplyTwo to the dummy variables in main(), so even thought
it looks like it is still using the dummy variables, it is actually using the ma
in() variables as they got assigned to the dummy ones.
~Example 8.A with comments I add
ed to teach you~
#include <iostream.h>
void multiply(int input, int input2) //Prototyp
e
int main()
{
int multiplyOne, multiplyTwo;
cout<<"Enter two numbers separated by a
space: ";
cin>>multiplyOne>>multiplyTwo;
Just like with cout<<, you can get multiple inputs in one cin>> line
multiply(multiplyOne, multiplyTwo);

//
/

/Take the inputs and do multiply()'s functions on it


}
void multiply(int input, int input2)
{
int answer;
answer=input*input2;
cout<<"\nThe answer is "<<answer<<".";
}
/*The above is in example file "8A_variableref.c
pp" in Ch.8 Example folder*/
Homework:
Make a program that gets user input on a number between 1-20. Using if() stateme
nts: if the number is between 1 & 10, go to a different function and tell the us
er that.
If the number is between 10 & 20, make the program go to a different function an
d add the inputed number with 35. Print that there's been an error if it is any
thing else.
The answer is in the Ch. 9 examples folder inside the main Examples folder.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 10: Return statem
ent
~
As I said before, the return statement can do a number of things. I taught you a
bout how it can end a program's execution. Now let's learn about it's other use:
returning
answers in multifunction programs. Say I want to find the product of two numbers
. We can do this is main() without "return", but for example purposes and also t
o try and
start making complicated programs, we will use two functions. To start this prog
ram, we include iostream.h and make a prototype (remember that word?), or the st
atement
for the second function. We will call the second function "multiply()". Your pro
gram should look like this so far:
#include <iostream.h>
void multiply(int number, int numberTwo);
If it doesn't, change it. Next, we start main(). The first thing to do to main()
is to define two integers and 1 long int for the answer. You can call the 2 int
s anything, but
we will use "a" and "b" in our example, and call the answer variable "answer". A
fter that, ask the user to enter 2 numbers using the 2 ints we definined and 2 c
in & cout
statements. You may also use one "cin>>" statement if you want. You should know
how to do this (if you haven't snoozed off like I did a few times while making t
his). Now, take the answer variable and write the sentance, "answer=multiply(a,b
);". This will call multiply() and use the variables a and b to do multiply()'s
functions. It will then assign the returning data from the second function to "a
nswer". Why this is different from the example shown in the previous lesson is b
ecause this time main() still is happening because the second function is called
and the value is received, and then main() continues. In the above example in t
he previous lesson, main() stops and the program finishes in the second function
. Now, finish up main by writing:

cout<<"\nThe product of those two numbers is "<<answer<<".";


Then close up main() with an ending brace and write the second function. Take th
e prototype and paste it to start the function. Then, this is where the return h
appens, put
the words:
return number*numberTwo;
in the function. That takes the two variables, multiplies them, and then sends t
he answer back out of the function to the answer variable. Think of the return s
tatement in this
case as simply a backup or sidekick for main(). But to make this send the answer
to a variable, you must declare the answer variable's value to this function. R
emember
the outline of that? Here is a model:
The variable that the value is being assigned to | The function name fol
lowed by the variables being used in that function
|
/
|
\
variableName=function(numberOfVariablesNeeded);
|
All the variables being
used
If you don't assign a variable's value to the return of a function, the return w
ill go nowhere and it will seem as if the second function never occured. Here is
the final, completed
source code for the program we just made in the first paragraph:
#include <iostream.h>
void multiply(int number, int numberTwo);
int main()
{
int a,b;
long int answer;
cout<<"Enter two numbers separated by sp
aces: ";
cin>>a>>b;
answer=multiply(a,b);
cout<<"\nThe product of those two number
s is "<<answer<<".";
}
void multiply(int number, int numbertwo)
{
return number*numbertwo;
}
/*The above is in Example file called "10A_retur
n.cpp" in Ch. 10 Example folder*/
One reason why you would use a different function to return a value you can do i
n main() is when you start making more complex programs. In more complex program
s, you
can save space in main() by using different functions, or you can organize and m
ake your programs more neater by dividing things up by functions. Either way, yo
u need to
know how to do this.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 11:Case & switch


statement
~
As I said earlier in this tutorial, if() statements are only used for numbers. W
hen it comes to characters, we use a case statement. A switch statement doesn't
play a big part
in the case statement. All it does is it gets the variable being tested ready fo
r case statements. I am not sure why it is there, but you need it before you sta
rt using case
statements. Now, first you must declare a switch statement. It is just like any
other function. You write switch and then the arguments. Inside the arguments, o
r parentheses,
you put the variable you will be testing. You just put the name. Here is a model
:
Write the switch statement
|
switch(variableName)
|
Put the name of the variable you are testing
{
~case statements~
}
After that, you start case statements. The case statements are the statements th
at test variables and work accordingly. Now, case statements look tricky and con
fusing,
but they aren't. Here is a model of the case statement:
Test the variable from the switch() statement for the letter
/ | \
case 'A' :
<------Notice how there is a ":"
there. That is just like a brace, except there is no ending one.
~what to do if the above is true~
<------Notice there is no ending sign. The c
ompiler knows when it ended by either the closing switch() brace, or another cas
e.
case 'B' : case 'C' :
\ | /
You can put two case statements in one line by separating them b
y a ":".
First you start off with a case statement inside the braces from switch(). You m
ust put characters in single quotes, NOT double quotes. It tests the following c
haracter. You
can put numbers there, but it is easier just to use if() statements for numbers.
After that, you put a ":". Now, if you want the computer to react to either tes
ts or both tests,
like if you want the computer to do the same thing for the case that a variable
is equal to A or a, then you put a second case statement after that, like in the
second case
statement in the model, but you must separate them by using a ":" in between eve
ry case statement in one line. The compiler keeps knowing to do the same thing i
n

different cases because until it reaches something other than "case", it knows t
o do the same thing to the chained together cases. So, once the compiler finds n
o more
case statements chained together, it considers everything until the next case st
atements as the instructions of what to do if the cases are true. So, you can pu
t multiple
case statements together separated by a ":", but once the compiler finds no more
case statements chained together, it considers everything until the next case s
tatements
as the instructions of what to do if the cases are true. Understand now? Good, b
ut heres an example program:
~Example 11.A "11A_cases.cpp"~
#include <iostream.h>
int main()
{
char a;
cout<<"Enter A for a star to show, B for a numbe
r, and C for a percent symbol: ";
cin>>a;
switch(a)
{
case 'A':case 'a':
cout<<"\n********";
case 'B':case 'b':
cout<<"\n99999999999";
case 'C':case 'c':
cout<<"\n%%%%%%%%%%%%";
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 12:Making your own include files
~
Before we begin, I want to tell you that all include files end in a .h in the fi
le name. That is what sets it apart from an ordinary source file. So include tha
t on your include files.
So, you've learned about functions, variables, if statements, case and switch st
atements, other include files, file input/output, reference variables, and a ton
more. Now it's
time that you can start creating your own include files. But what makes an inclu
de file any different than a normal source file? Because the compiler has to kno
w if the file
has already been included earlier in any source code file so it can give an erro
r if a mistake happens that you accidently include it a second time in the same
source file.
That's what I will teach you here. Now, in any include file, it is best to comme
nt about the file's functions so anybody looking at them can know what it does.
So at the top
of your own include files, add in all the functions it does. That way you help p
eople understand what the functions do and how to call them. Next, the statement
to tell the
compiler not to include it a second time in one source file is a preprocessor di
rective. The first command is written as:

#ifndef _NAME_H
This means that if the include file has not already been defined, or included in
the source code including it, that it is okay to include it. After that you put
a _ to start the file
name. You then write the file's name without the .h part after the _ without spa
ce inbetween. Then you write another _ inbetween the name and "H". You then add
an H at
the end of the line. That means, "if the file ---- is not included already, cont
inue on including it.". If it already is included in the source file including i
t, the compiler will give an
error. If it goes well, then you define the file. To do that, you write the line
:
#define _NAME_H
It is just like the first preprocessor directive except you replace ifndef with
define. "define" makes it define the include file's source, or tell the compiler
that it is now being
included so don't include it again in the same source file. After that, you just
continue on with the source like normal. But remember: the point of an include
file is to add
definitions so any program can include it without having to define everything it
self. If you just use and include file to make a program, that isn't good and yo
u should take out
the above preprocessor directives and takeout the .h prefix on the file's name.
Finally, when you are done with all the include file's source, and I mean totall
y complete, you
add the following line after the last line:
#endif
That tells the compiler that the include file is done and that that's the source
code the compiler should be on the lookout for to prevent double inclusions. Th
ere you have it!
Now you can make your own include files! By the way, so there's no confusion, yo
u may include other include files in an include file. In fact, most do. I have i
ncluded examples
of include files I made myself in the Ch. 12 examples folder inside the main exa
mples folder. They are quite simple, but they are enough to give you an idea of
this lesson.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Lesson 13: Classes
~
In C++, there are times when your code is complex and confusing with alot of fun
ctions and variables. That is when classes become a handy tool to make it look s
imple.
Classes are like a suitcase for C++ code, in that it carries everything you will
use in a neat arrangement. In classes, there are public members and private mem
bers. First,
we will go over a model of a class:
Declare a class and put its name
/ \
class className
{

public:
~public members~

<------Everything th

private:

<----------Start def

~private members~

<--------Everything

at's public
ining private members
that's private
};
<-----!!!Notice the semi colon! This is *
required* after the closing brace on any class declaration
Now, you probably are lost and confused. That's what you should be or else you d
on't need to read this tutorial. We start off by declaring a new class. Unlike m
any other
commands and functions in C++, we actually declare it and start adding to it the
n, unlike makeing prototypes and making them later. Next we name the class. It c
an be
anything, but it is best to call it something that relates to the contents. Like
if the class if full of math variables and functions, you might call it "mathem
atics". After that, we
start defining public and private members. This is where you learn the real func
tions of a class. The names give away most of the meaning, but you must learn ho
w they do.
Public members are variables and functions that any part of the source code can
use. That means it can be used or called in main(), or it can be used in any oth
er things.
Private means that only the public members may use the private contents. That is
why private members get declared after public members, so it goes in order. So
if I had
the public function "void getAnswer()" and the private variable "answer", only g
etAnswer() may use the variable "answer". So main() or any other general functio
ns may not
use it. So you declare the functions and variables in their appropriate catagori
es, depending on how and where you will use them. But you may only use a name fo
r something
once, regardless of it being private or public. Like if I had "int b" in the pub
lic section, I can't put another int called b in the private section. But now th
ere comes a style that is so
common, that if you don't use it, your programs will look awkward and funky at f
irst. That style is defining most, if not all, of the variables/functions outsid
e of the class instead
of when you declare them. So if I put 3 variables and 5 functions in a class, it
would be best to give them their definitions and values outside of the class. B
ut there is a special
way that you call the contents of a class, which I will cover in a minute. Anywa
y, after you declare all of the contents in their appropriate catagories, you th
en close up the
class and continue on with the program. Now, as I just said, there is a way to c
all or define or give value to anything inside a class. Actually, it is required
. Instead of simply
typing the name of the function or variable, you include the data type of the va
riable/function you will be defining/calling and then you write the name of the
class and then
you write two, count 'em, two ":"'s. So a model of what I just explained looks l
ike this:

datatype className::
Now, after the two ":"'s, you put the name of the function/variable you are abou
t to define. So if I was going to define "void number" from the class called "ma
thematics",
I would write that like this:
void mathematics::number()
After that, you just define it like normal.
To call it, you make an instance of the class, or replace the data type of any n
ew variable with the name of the class, like for class name Math, I would first
write, "Math variableName". Then, I would call a class function by typing the in
stance's name and then a period followed by the name of the function, like:
classInstanceName.classFunction();
Just the function name, like you never made the class.
Lesson 14:Type conversion
~
In C++, there comes a time where you need to change a variable's data type. It m
ay be to do a special trick, or you need it for some function to work properly.
Either way,
there is a way in C++ that is extremely simple. The variable you are converting
must already be defined and declared. You also may not fool around and convert a
data type
to the same data type or a similar one, i.e. converting an int to a long int. So
, to convert a variable, you simply either:
1. Take the target data type and put that in parentheses, and leave the name of
the variable following it outside of the parentheses. Example:
char a;
...
(int) a;
//This converts a character to
an int. In C++, that simply returns the character's ASCII value.
2. Take the target data type and write it normally, but put the variable name in
parentheses. Example:
char a;
...
int (a);
But there are rules to converting. If you convert a char to an int, it just retu
rns its ASCII value. If you convert an int to a float or any decimal data type,
it will simply add zeros
after the decimal because an int doesn't hold decimal numbers. Just use your bra
in when converting.

$Ending Part$
~
Well, this leaves us to the end of this C++ tutorial. I hope you learned alot as
I spent alot of time on this. Look at the Future References file I included to
help you learn more

after you finished this.

Das könnte Ihnen auch gefallen