Anda di halaman 1dari 28

Lesson 1: The basics of C++

I am writing this for those people who want to learn how to program in
C++, especially those who had trouble. It is for those of you who want a sens
e of accomplishment every time your program works perfectly. If you want the s
ense of accomplishment, read on.
C++ is a programming language. It is a programming language of many
different dialects, just like each language that is spoken has many dialects. I
n C though, they are not because the "speakers" live in the North, South, or gre
w up in some other place, it is because there are so many compilers. There are
about four major ones: Borland C++, Microsoft Visual C++, Watcom C/386, and DJGP
P. You can download DJGPP http://www.delorie.com/djgpp/ or you may already have
another compiler.
Each of these compilers is a little different. The library functions of one wil
l have all of the standard C++ functions, but they will also have other function
s or, continuing the analogy, words. At times, this can lead to confusion, as c
ertain programs will only run under certain compilers, though I do not believe t
his to be the case with the programs in these tutorials.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
If you don't have a compiler, I strongly suggest you get one. A simple one is go
od enough for
my tutorials, but get one.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C++ is a different breed of programming language. It has only a few keywords fo
r DOS, and it has no keywords to use for output. This means that almost everyth
ing is stored in a header file. This gives the use of many functions. But lets
see a real program...

#include <iostream.h>
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello World!";
return 0;
}
That does not look too hard, right? Lets break down the program and then look a
t it. The #include is a preprocessor directive which tells the compiler to put
code in the header file iostream.h into our program! By including header files,
you ~can gain access to many different functions. For example, the cout functi
on requires iostream.h.

The next thing is int main() what this is saying is that there is a function cal
led main, and that it returns an integer, hence int. Then those little braces (
{ and } ) are used to signal the beginning and ending of functions, as well as
other code blocks. If you have programmed in Pascal, you will know them as BEGI
N and END.
The next line of the program may seem strange. If you have programmed in other
languages you might think that print would be used to display text. However, in
C++ the cout function is used to display text. It uses the << symbols, known a
s insertion operators. The quotes tell the compiler that you want to output the
literal string as-is. The ; is added to the end of all function calls in C++.
The penultimate line of code is ordering main to return 0. When one returns a v
alue to main, it is passed on to the operating system. As a note, declaring int
main() or void main() both will generally work. It is accepted practice to som
e to declare main as a void, but to others it is
extremely upsetting. Previously, these tutorials had used void main, however, t
his is NO LONGER recommended, as it does not conform to the ANSI standard.
After, the brace closes off the function. You can try out this program if you
want, just cut and paste it into the IDE of a compiler such as DJGPP, or save it
to a file ending with a .cpp extension, and use a command-line compiler to comp
ile and link it.
Comments are extremely important to understand. When you declare that an area
is a comment, the compiler will IGNORE it. To comment it is possible to use ei
ther // , which declares that the entire line past that point is a comment, or
it is possible to use /* and then */ to block off everything between the two as
a comment. Certain compilers will change the color of a commented area, but s
ome will not. Be certain not accidently declare part of your code a comment. N
ote that this is what is known as "commenting-out" a section of code, and it is
useful when you are debugging.
So far you should be able to write a simple program to display information typed
in by you, the programmer. However, it is also possible for your program to ac
cept input. the function you use is known as cin>>.
Wait! Before you can receive input you must have a place to store input! In pr
ogramming, these locations where input and other forms of data are stored, are c
alled variables. There are a few different types of variables, which must be st
ated. The basic types are char, int, and float.
Char is used to create variables that store characters, int is used to create va
riables that store integers (numbers such as 1, 2, 0, -3, 44, -44), and float is
used to delare numbers with decimal places. In fact, they are all keywords tha
t are used in front of variable names to tell the compiler that you have created
a variable. That is known as "declaring a variable". When you declare a varia
ble, or variables, you must end the line with a semi-colon, the same as if you w
ere to call a function. If you do not declare the variable you are attempting t
o use, you will receive numerous error messages and the program will not run.

Here are some examples of declaring variables:


int x;
int a, b, c, d;
char letter;
float the_float;
It is not possible, however, to declare two variables of different types with th
e same name.
#include <iostream.h>
int main()
{
int thisisanumber;
cout<<"Please enter a number:";
cin>>thisisanumber;
cout<<"You entered: "<<thisisanumber;
return 0;
}
Let's break apart this program and examine it line by line. Int is the keyword
that is used when delcaring a variable which is an integer. The cin>> sets the
value of thisisanumber to be whatever the user types into the program when promp
ted. Keep in mind that the variable was declared an integer, which means the ou
tput will be in the form of an integer. Try typing in a sequence of charaters,
or a decimal when you run the example program to see what you get as a response.
Notice that when printing out a variable, there are not any quotation marks.
If there were quotation marks, the output would be "You Entered: thisisanumber."
Do not be confused by the inclusion of two separate insertion operators on a l
ine. It is allowable, as long as you make certain to have each separate output
of variable or string with its own insertion operator. Do not try to put two var
iables together with only one << because it will give you an error message. Do
not forget to end functions and declarations with the semi-colon(;). Otherwise
you will get an error message when you try to compile the program.
Now that you know a little bit about variables, here are some ways to manipulate
them. *, -, +, /, =, ==, >, < are all operators used on numbers, these are the
simple ones. The * multiplies, the - subtracts, and the + adds. Of course, th
e most important for changing variables
is the equal sign. In some languages, = checks if one side is equal to the othe
r side, but in C++ == is used for that task. However, the equal sign is still e
xtremely useful. It sets the left side of the equal sign, which must be one AND
ONLY one variable, equal to the right side. The right side of the equal sign i
s where the other operators can be used.
Here are a few examples:
a=4*6; //(Note use of comments and of semi-colon) a is 24
a=a+5; // a equals the original value of a with five additional units
a==5 //Does NOT assign five to a. Rather, it checks to see if a equals 5.
The other form of equal, ==, is not a way to assign a value to a variable. Rath
er, it checks to see if the variables are equal. It is useful in other areas of
C++ such as if statements and loops.
You can probably guess what the < and > are for. They are greater than and less
than checks.
For example:
a<5 //Checks to see if a is less than five
a>5 //Checks to see if a is greater than five
a==5 //Checks to see if a equals five, for good measure
---
Note: My homepage is http://www.cprogramming.com. My email is webmaster@cprogra
mming.com. Please email me with comments and or suggestions. If you want to us
e this on your own site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Learning C: lesson 2
Hello, this is Alexander. Since I finally got an email from someone who liked m
y previous
lesson, I am going to make the second installment. This one will be about varia
bles, and
stuff like 'if' statements.

'IF' is the most important word in programming for many programs. Without it th
ere is no
conditional statements. This means that there can be only one way a program can
execute.
It would almost impossible to make a program without this one simple word.

There are many things to understand when using IF statements. First, you must u
nderstand
stuff like OR NOT etc. This are the most important, so I will describe how to u
se them in
C and C++ programming below: (NOTE: ZERO IS FALSE! ONE IS TRUE!)

NOT: This just says that the program should reverse the value...for example NOT(
1) would be
0. NOT(0) would be 1. NOT(any number but zero) would be 0. In C and C++ NOT i
s written
as - ! - just one simple little character. It is very useful and can save lots
of time.

AND: This is another important command, and it is used to say that if this AND t
his is
true... for example (1)AND(0) would come out as 0. (1)AND(1) would come out as
1. (ANY
REAL NUMBER BUT ZERO)AND(0) would be 0. (ANY REAL NUMBER BUT ZERO)AND(ANY REAL
NUMBER BUT
ZERO) would be 1. The AND is written as - && - in C++. It is just two simple c
haracters.

OR: Very useful is the OR statement! For example (1)OR(0) would be 1! (0)OR(0)
would be
0. (ANY REAL NUMBER)OR(ANY REAL NUMBER BUT ZERO) would be 1! It is simple, eit
her one can
be true and make the whole thing true. The OR is written as - || - in C++. It
is also two
simple characters.

The next thing to learn is to combine them... What is !(1 && 0)? Of course, it
would be
1. This is because 1 && 0 evaluates two 0 and ! 0 equals 1.

Try some of these...they are not hard. If you have questions about them, you ca
n email me
at lallain@concentric.net.

A. !(1 || 0) ANSWER: 0
B. !(1 || 1 && 0) ANSWER: 0 (AND is evaluated befo
re OR)
C. !((1 || 0) && 0) ANSWER: 1 (Parenthesis are usefu
l)

If you find you enjoy this you might want to look more at Boolean Algebra, which
is also
very helpful to programmers as it can be good for helping program conditional st
atements.

IF is used like this IF(TRUE)


{ DO WHAT IS IN THE BRACKETS }

ELSE is basically ELSE


{ DO WHAT IS IN THE BRACKETS }

Let's look at a simple program for you to try out on your own...

#include <iostream.h> //For output


#include <conio.h> //For getch()
void main() //Most important part of the program!
{
int age; //Need a variable...
cout<<"Please input your age: "; //Asks for age
cin>>age; //The input is put in age
if(age<100) //If the age is less than 100
{
cout<<"You are pretty young!"; //Just to show you the output
}
if(age==100) //Remember, if the age equals 100 needs
two =
{
cout<<"You are old"; //Just to show you it works...
}
if(age>100)
{
cout<<"You are really old"; //Proof that it works for all conditions
}
}

Now, this program did not use && || ! or anything in it. This is because it did
n't need
too. I think you should probably be able to make your own if statements with th
em without
having to worry too much about problems. As always, you can email me at
lallain@concentric.net

Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri


c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Lesson 3: Loops
This is the third installment of the Lessons in C programming tutorials created
by me,
Alexander. In this lesson I will cover loops. Loops basically do what it sound
s like,
loop. If you have read lesson 2 you should understand some Boolean expressions.
If you do
not, you should read it again. When working with loops it is important to under
stand truth
and false. Maybe you should try doing some truth tables with problems.

There are basically 3 types of loops. FOR, WHILE, DO WHILE Each of them has th
eir uses.
They are all outlined below.

FOR - FOR loops are the most useful type, I believe. The layout is for(variable
initialization, conditional, incrementing variable) It is very versatile, and t
he layout
can be changed somewhat. Basically, the variable initialization allows you to e
ither
declare a variable and give it a value, or give a value to another variable. Se
cond, the
conditional statement. What it does is it says that while the conditional is tr
ue then it
would do what in is in the body. Third, the incrementing variable section. It
does not
have to increment a variable. It can decrement, which is subtracting one, or it
can
perform various other manipulations on the variable.

Ex. #include <iostream.h> //We only need one header file


void main() //We always need this
{
//The loop goes while x<100, and x
has one
for(int x=0;x<100;x++)/*THE LOOP*/ //added to it every time th
e loops
{
cout<<x<<endl; //Outputting x
}
}

This program is a very simple example of a for loop. x is set to zero, while x
is less
than 100 do cout<<x<<endl; add 1 to x until the loop ends. Pretty simple to und
erstand,
but it is a very powerful loop, and much better than WHILE and DO WHILE loops.

WHILE - WHILE loops are very simple, but not as useful as FOR loops. The basic
structure
is...WHILE(true) then do whatever is in the body. The truth could be x==1 or wh
ile(x!=7)
(x does not equal 7)
Ex. #include <iostream.h> //We only need this header file
void main() //Of course...
{ int x=0; //Don't forget to declare variables
while(x<100) //While x is less than 100 do
{
cout<<x<<endl; //Same output as the above loop
x++; //Adds 1 to x every time it repeats
}
}

This was another pretty simple example, but it is longer than the above FOR loop
, showing
why I like for better than while, though while is a very easy loop to use, so if
you are
having trouble then you can use it, but try to use for.

DO WHILE - DO WHILE loops are useful for only things that want to loop at least
once.
basically it goes DO { THIS } WHILE(TRUE)

Now, it is your turn to try and do a loop! make a DO WHILE loop that does what
the above
programs do...output 0 to 99! It is not hard, if you have trouble email me at
lallain@concentric.net and I will give you some help... Best of luck :) Check b
ack again for
more programming in C!
#include <iostream.h>
int main()
{
int x=0;
do while(x<100)
{
cout << x << endl;
x++;
}
}
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri
c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 4: Functions

Now that you have learned all about variables, loops, and if statements it is ti
me to learn
the next thing in programming: Functions. Obviously, you should have a good ide
a about
what a function is, as you have used ones like cout before. However, this lesso
n will be
more in detail about not only functions that are already made, but about making
your own,
or maybe I will continue this later...

A good way to describe a function is to show its prototype. That means, what it
should return,
and what it should take as an argument. For example, the prototype of getch() i
s... int
getch(void); The int means that it returns an integer, the void means that it do
es not take an
argument. Now, you may know that getch returns a character! However, that does
not mean it
must return a character. The fact that the return type is an integer makes no d
ifference,
because the ASCII character set does not care what type of number it is, as long
as it is a
number...don't worry if you don't understand, it is not too important right now.

What is important is that you understand prototypes. Another prototype is... in


t kbhit(void);
It returns an integer, and it takes no value. Now that I hope you understand th
is then you
will be able to use the help files much more easily, and I can go into more abou
t functions.
First, what functions are useful.

There are many useful functions, and often they are hard to find. For Turbo C++
Lite some
useful functions include, but are no limited to:

cout<< iostream.h output


cin>> iostream.h input
int getch(void) conio.h get characters
void clrscr(void) conio.h clear screen

Okay, you might be thinking that this is nothing! Four measly functions, and yo
u are
right! If there were only a few functions then C/C++ would not be useful. Howe
ver, a lot
of programs do not need all that many functions. Of course, I suggest that you
know ever
function that you can, or at least the name. For this purpose, I will be postin
g an entire
listing of ever function that I can find out of either help or books I have read
. However,
for now, these are probably the most useful functions. After all, if you can cl
ear the
screen, get input and output, and get keypresses, which are useful for stopping
the program
from immediately going back to the IDE you can do quite a bit! Believe me, ther
e are a few
specialized, but very useful functions, the thing is, you don't really need to u
se them all
the time! If you have a problem with a function that you need, and I have not p
ut up my
list yet, then email me at lallain@concentric.net, and I will find you what you
need!
Anyway, after that long spiel on not needing a lot of functions, I am going to s
how you how
to make your own functions! Wow, I can do that? Of course, otherwise C/C++ wou
ld not be
useful! So, prepare to learn how to make functions.

First let me give you an entire example program. Then we will look at it, and l
earn how to
make our own programs.

#include <iostream.h>
#include <conio.h>
int mult(int x, int y);
void main()
{
int x, y;
cout<<"Input a number, and what number to multiply it by";
cin>>x>>y;
cout<<endl<<mult(x, y);
getch();
}
int mult(int x, int y)
{
return x*y;
}

How is this useful...Well, in this program the function is totally useless, and
it can only
multiply integers! But this is just to show you how to make functions, after yo
u
understand the basics I hope you will be able to do anything yourself.

What my example does: #includes...basic includes What is int mult(int x, int y);
? That is
a prototype of the function, without it you would not be able to use mult! What
is void main()? You should know that. What is cout<<endl<<mult(x,y); Well, bas
ically it
puts us down a line, and then it outputs what mult returns. More on this later.
What is

int mult(int x, int y)


{
return x*y;
}

Well, it is a function! It says that the return type is an integer. When the ke
ywork
return is used it says that the function mult has a value of whatever x*y would
be...as it
says return x*y. The two ints that it takes are x and y. So it multiplies
them and returns
that value. Then outputs mult(x, y); It is perfectly legal. Perhaps it would
help if you
think of it as saying that the function mult has a value of whatever x*y is. Th
is is not
true really, it just returns that value, and you can do whatever you want with i
t, but I
hope it helps.

What can you do? You can make void functions that do anything...

#include <iostream.h>
void function(void);
void main()
{
function();
}
void function(void)
{
cout<<"This is a useless and totally wasteful function";
}

What is does is declare that there is going to be a function, by prototyping, an


d then at
the bottom the function is defined, and it only does one thing...outputs "This i
s a useless
and totally wasteful function" However, what if you wanted to do something that
took 3
lines four hundred times in different places? Say,

#include <iostream.h>
void function(void);
void main()
{
LOTS OF CODE THAT NEEDS TO OUTPUT Line 1Line 2Line 3
}

void function(void)
{
cout<<"Line 1";
cout<<"Line 2";
cout<<"Line 3";
}

That, aside from the fact that it is a bad example, is where you would use it.
When you
need to call something a lot of times, but don't want to cut and paste. Functio
ns are very
useful, and I hope I explained them well enough for you to understand.

Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri


c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 5: switch...case

I know that this is probably a let-down, after you learned all about functions,
but
switch...case is important to know. After all, it can save space with if statem
ents, and
it is useful. Besides, I couldn't think of anything else that I wanted to write
about.

Switch...case looks like this:

switch(expression or variable)
{
case it equals this:
do this;
break;
case it equals this:
do this;
break;
case it equals this:
do this;
break;
...
default
do this
}

So, it works like this. The expression or variable has a value. The case says
that if it
has the value of whatever is after this case then do whatever follows the colon.
The break
says to break out of the case statements. Break is a keyword that breaks out of
the
code-block, surrounded by braces, that it is in. So unless you want it to try t
he next
case then use break. --You can also use it to break out of loops, something that
I failed
to mention at the time.--

What is it used for, the switch...case? Well, let's say that you are writing a
menu
program, then you would want to process some input, right? Well, you would want
to use a
switch...case statement to process more than one input, because it is more easil
y used than
if statements.

Here is an example program:


#include <iostream.h>
#include <conio.h>

void main()
{
char input;

cout<<"1. Play game";


cout<<"2. Load game";
cout<<"3. Play multiplayer";
cout<<"4. Exit";
input=getch(); //Remember I said you don't need many fu
nctions...
switch(input)
{
case 1:
playgame();
break;
case 2:
loadgame();
break;
case 3: //Note use of : not ;
playmultiplayer();
break;
case 4:
break;
default:
cout<<"Error, bad input, quitting";
}
}

If you are not understand this, then try putting in if statements for the case s
tatements.
Also, the reason exit works with a break is that after you break out of the swit
ch
statement then it would be the end of the program. The same thing would be for
default.
If you don't like that, then make a loop around the whole thing. I know I did n
ot
prototype the functions, but it was a very simple example. You could easily make
a few
small functions.

Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri


c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 6: An introduction to pointers

Welcome to the sixth in my series of tutorials. This is one about a topic that
you may or
may not have already heard about...pointers. What are they, what do they do, wh
y do we
care? First, why do we care.

We care about pointers because they allow access to memory, the also make array-
access
faster, they are also somewhat necessary to understand some functions. Most imp
ortantly,
you will see them a lot in other people's code. You may not need to use them mu
ch, but it
will be tremendously important to understand them.

Second, what do they do. Well, I might as well address this issue as well as wh
at they are
at the same time. Pointers are what they sound like...pointers. They point to
locations
in memory. Picture this: a big jar that holds one thing, the name of another ja
r. In the
other jar is the value of an integer. The jars are memory locations. The jar t
hat holds
the name of the other jar is a pointer. It points to the other drawer.

How can you use this? Well, look at this little piece of code:

#include <iostream.h>

void main()
{
int x;
int *pointer;
pointer=&x;
cin>>x;
cout<<*pointer;
}

Guess what! The cout outputs the value in x. Why is that? Well, look at the c
ode. The
integer is called x. Then a pointer to an integer is defined as pointer. The a
strick(*)
symbol means that it is a pointer. Then I give the memory location of x to poin
ter by
using the ampersand(&) symbol. It gives the memory location of the variable it
is in front
of. For example, if the jar that had an integer had a ampersand in it it would
output its
name, or location.

Then the user inputs the value for x. Then the cout uses the * to put the value
stored in
the memory location of pointer. Huh? Picture the jars again. If the jar with
the name of
the other jar in it had a * in front of it it would give the value stored in the
jar with
the same name as the one in the jar with the name. It's not too hard, the * giv
es the
value in the location. The unastricked gives the memory location.
I hope this has been at least an interesting introduction to pointers. I do not
suggest
that you play around with them too much as you can do unpleasant things on your
computer,
but you now should have a better understand of what they are.

Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri


c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 7: Structures
Welcome to the seventh lesson. This is my first lesson that I will explain clas
ses. However,
I will explain more about structures, because they can be useful, and they are a
good way
to get a feel for how a class works.
What are structures? They are a way to store more than one data-type under the
same name.
Fore example:
#include <string.h> //For strcpy
struct database
{
int age;
char name[20];
float salary;
};
void main()
{
database employee;
employee.age=22;
strcpy(employee.name, "Joe");
employee.salary=12000.21;
}
Don't worry about the name[20]. That is just an array. It can hold more than o
ne
character all called under the same name. They are used like strings. I will d
o my next
lesson on arrays, I promise, because they are very important. The struct databa
se declares
that database has three variables in it, age, name, and salary.
Eventually, you can use database like a variable type like int. You can create
an employee
with the database type like I did above. Then, to modify it you call everything
with the
employee. in front of it. You can also return structures from functions by defi
ning their
return type as a structure type. Example:
struct database fn();
You can make arrays of structures as well. I will show you how to do this in l
esson 8.
That will be up in a few days. I suppose I should explain unions a little bit.
They are
like structures except that all the variables share the same memory. When a un
ion is
declared the compiler allocates enough memory for the largest data-type in the u
nion.
To access the union you use the . like in structures. Also, if you are accessin
g the union
of structure through a pointer use the -> operator. for example, database->empl
oyee . The
most useful thing about unions is that you can manipulate the bytes of the data-
types. You
might want to see what you can do if you understand that sort of stuff. Persona
lly, I have
never used a union.
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri
c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Lesson 8: Array basics
This is the eight installment of my lessons, and it is on arrays. Arrays are es
sentially a way
to store many values under the same name. You can make an array out of any data
-type,
including structures. For example, you could say
int examplearray[100]; //This declares an array
This would make an integer array with 100 slots, or places to store values. The
only difficult
thing is that it starts off with the first index-number, that is, the number tha
t you put in
the brackets to access a certain element, is zero, not one!
Think about arrays like this: [][][][][][] Each of the slots is a slot in the
array, and
you can put information into each one of them. It is like a group of variables
side by side
almost.
What can you do with this simple knowledge? Lets say you want to store a string
, since C++ has
no built-in datatype for strings, in DOS, you can make an array of characters.
For example:
char astring[100];
Will allow you to declare a char array of 100 elements, or slots. Then you coul
d get it from
the user, and if the user types in a long string, it will all go in the array.
The neat thing
is that it is very easy to work with strings in this way, and there is even a he
ader file
called STRING.H. I will have a lesson in the future on the functions in string.
h, but for now,
lets concentrate on arrays.
The most useful aspect of arrays is multidimensional arrays.
For example:
int twodimensionalarray[8][8];
Think about multidimensional arrays:
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]
This is a graphic of what a two-dimensional array looks like when I visualize it
.
declares an array that has two dimensions. Think of it as a chessboard. You ca
n easily use
this to store information about some kind of game, or write something like tic-t
ac-toe. To
access it, all you need are two variables, one that goes in the first slot, one
that goes in
the slot. You can even make a three dimensional array, though you probably won'
t need to. In
fact, you could make a four-hundred dimensional array. It is just is very confu
sing to visualize.
Now, arrays are basically treated like any other variable. You can modify one va
lue in it by
putting:
arrayname[arrayindexnumber]=whatever;
You will find lots of useful things to do with arrays, from store information ab
out certain
things under one name, to making games like tic-tac-toe. One little tip I have
is that you use
for loops to access arrays. It is easy:
#include <iostream.h>
void main()
{
int x, y, anarray[8][8];//declares an array like a chessboard
for(x=0; x<8; x++)
{
for(y=0; y<8; y++)
{
anarray[x][y]=0;//sets all members to zero once loops is done
}
}
for(x=0; x<8;x++)
{
for(y=0; y<8; y++)
{
cout<<"anarray["<<x<<"]["<<y<<"]="<<anarray[x][y]<<" ";//you'll see
}
}
}
Here you see that the loops work well because they increment the variable for yo
u, and you only
need to increment by one. It is simple, and you access the entire array, would
you want to use
while loops?
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri
c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Lesson 9: Strings
This lesson is one on strings. Strings are really arrays, but there are
some different
functions that are used for strings, like adding to strings, finding the length
of strings, and
also of checking to see if strings match. Strings are basically sentences, or w
ords. Like,
"This is a string".
Strings are basically character arrays. For example, to declare a strin
g of 50 letters, you
would want to say:
char string[50];
This would declare a string with a length of 50 characters. Don't forget that a
rrays begin at
0, not 1 for the index-number. Also, a string ends with a null character, liter
ally a '/0'
character. But, just remember that there will be an extra character on the end
on a string. It
is like a period at the end of a sentence, it is not counted as a letter, but it
still takes up
a space.
What are strings useful for? Well, for one thing, you might want to get a perso
n's name. If you
wanted to, you would need a string, because a name can't fit in one variable! I
t is, however, a
collection of characters, and so fits nicely into a character array.
Now, what if you want to input a string? Well, if you try to use cin>> then it
won't work! It
terminates at the first space. However, you can use the function gets(char *s);
.
Gets is basically a function that reads in a string and stops reading at the fir
st new-line, for
example, when a user hits enter. Gets is in stdio.h. All you do, is put the nam
e of the array and it will work out,
because the pointer char *s is basically one way you tell a function that you wi
ll be passing an
array, although it is a pointer, it is still the string you give. Essentially,
char *s points to
a string, and you can access this string just like an array.
I will touch upon this relationship as described above in another lesson that wi
ll be a more
advanced lesson on pointers and arrays.
Anyway, to get a string from a user you want to use gets. An example program of
this would be:
#include <stdio.h> //For gets
#include <iostream.h> //For all other input/output functions

void main()
{
char astring[50]; //This declares a character array that can be
used as a string
cout<<"Please enter a string"; //You should know this one!
gets(astring); //The user will input a string(with spaces)
cout<<"You input: "<<endl; //You know this one too!
cout<<astring; //This is how you output character arrays, but
not others!
}
Ok, thats pretty simple. But, what if you want to use some of the nifty functio
ns from string.h?
Well, these include the following functions:
int strcmp(const char *s1, const char *s2);
strcmp will accept two strings. It will return an integer. This integer will e
ither be:
Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.
Strcmp is case sensitive.

int strcmpi(const char *s1, const char *s2);


strcmp will accept two strings. It will return an integer. This integer will e
ither be:
Negative if s1 is less than s2.
Zero if the s1 and s2 are equal.
Positive if s1 is greater than s2.
Strcmpi is not case sensitive, if the words are capitalized it doesn't matter.
char *strcat(char *desc, char *src);
strcat is short for string cacatenate, which means to add to the end, or append.
It does just this,
the first string is what the second string is stuck on the end of. It basically
returns the
cacatenated string. The first string will also have the entire string added to
it.
char *strupr(char *s);
strupr converts a string to uppercase. It also returns a string, which will all
be in uppercase.
The input string, if it is an array, will also all be uppercase.
char *strlwr(char *s);
strlwr converts a string to lowercase. It also returns a string, which will all
be in uppercase.
The input string, if it is an array, will also all be uppercase.
size_t strlen(const char *s);
strlen will return the length of a string, minus the termating character(/0). T
he size_t is
nothing to worry about. Just treat it as an integer.
Some of the stuff in the strings may be confusing. The const char *s stuff, for
example. But,
just remember that basically all of that will be a string! It doesn't matter wh
at the code is
right now, just what the functions do.
Now, a small program using many of the string functions!
#include <iostream.h> //For cout
#include <string.h> //For many of the string functions
#include <stdio.h> //For gets
void main()
{
char name[50]; //Declare variables
char lastname[50]; //This could have been declared on the last line...
cout<<"Please enter your name: "; //Tell the user what to do
gets(name); //Use gets to input strings with spaces or just to get
strings after the user presses enter
if(!strcmpi("Alexander", name)) //The ! means not, strcmpi returns 0 for equa
l strings
{ //strcmpi is not case sensitive
cout<<"That's my name too."<<endl; //Tell the user if its my name
}
else //else is used to keep it from always output
ting cout<<"That's not my name."
{
cout<<"That's not my name."<<endl;
}
cout<<"What is your name in uppercase..."<<endl;
strupr(name); //strupr converts the string to uppercase
cout<<name<<endl;
cout<<"And, your name in lowercase..."<<endl;
strlwr(name); //strlwr converts the string to lowercase
cout<<name<<endl;
cout<<"Your name is "<<strlen(name)<<" letters long"<<endl; //strlen returns
the length of the string
cout<<"Enter your last name:";
gets(lastname); //lastname is also a string
strcat(name, " "); //We want to space the two names
apart
strcat(name, lastname); //Now we put them together,we a space in the
middle
cout<<"Your full name is "<<name; //Outputting it all...
}

Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri


c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Lesson 10: File I/O(part
1)
This is a slightly more advanced topic than what I have covered so far,
but I think that it
is useful, and I think it will be useful to many people. File i/o is basically
reading, and
writing files. This lesson will only cover text files, that is, files that are
readable
through a text editor, as opposed to binary files(exes for example). It will no
t cover a great
deal, for example, this lesson will not deal with searching files or reading spe
cific data from
files. It will merely be concerned with opening, writing, and reading text file
s. Don't worry
though, lesson 11 will cover much more on this topic.
Well, how does it all start anyway? Files have their own specific funct
ions to use, as
well as their own data-type, called a FILE(There is more to this, but right not
it is not
important, and it will be explained later, when it is useful). The way to use t
he FILE type is
the same way as using an integer, or a float, or a char:
FILE *newfile; //Creates a FILE called newfile(don't forget that it is a pointer
)
Now, we can't use this unless there is a way to give the FILE(*newfile)
a file to point to.
The way this works is that it is what is called a stream. That means that it is
where the
output will go to. To direct *newfile to a file the command to use is FILE *fop
en(const char
*filename, const char *mode), found in stdio.h. It simply returns a pointer to
a FILE, but it is easy enough to use. For example:
FILE *newfile: //Creates a FILE called newfile
newfile=fopen("c:\AUTOEXEC.BAT", "r");//open up for reading your autoexec.bat fi
le, and assign
//it t
o newfile
Basically, fopen accepts two strings. One of them is the file name, inc
luding the path,and
the other is what the file will be used for(the mode). In this case, the r desi
gnates the file will only be opened for reading. Therefore, the file cannot be
modified while it is open. That is probably a good idea, because editing your a
utoexec.bat file with giberish is not a good idea!
For a reference here is a chart listing the different ways you open a fi
le:
r Open for reading only.
w Creates a file for writing. If a file by that name already exists, it wi
ll be overwritten.
a Append; open for writing at the end of the file, or create the file if i
t does not exist.
r+ Open an existing file for reading and writing.
w+ Create a new file for reading and writing. If a file by that name alread
y exists, it will
be overwritten.
a+ Open for append; open (or create if the file does not exist) for update
at the end of the
file.
Keep in mind that each of these has a different use, and that you should
choose the one
most appropriate for you task. For now however, lets concentrate on reading a f
ile.
Now, let's say you want to print the contents of autoexec.bat to your sc
reen. Assuming you
want to make a program to do this you would need a function for reading from a f
ile. There are numerous useful ones, but for now we will use int fgetc(FILE *st
ream)(Note that it returns an int, but the range will still be printable(so it i
s the same as a char), defined in iostream.h. Basically, fgetc will get the nex
t character from a file you give it(that is, the stream you give it). An exampl
e would be the following code to display the first few characters of your autoex
ec.bat file:

#include <iostream.h> //For cout


#include <stdio.h> //For all file i/o functions
void main()
{
int count=0; //Just a variable to keep from reading the file forever.
FILE *afile; //We need a FILE to point to the stream to allow access to the f
il
afile=fopen("c:/AUTOEXEC.BAT", "r"); //Open up the autoexec.bat file for readi
ng
//No, I do not know why it must be a forward slash.
while(count<10)
{
cout<<(char)fgetc(afile); //Notice that fgetc returns an int, which can be p
rinted.
//Please note the use of (char) to 'typecast' the returned integer. Tha
t means that it makes
//it into a printable character from the number. There is more on this
in lesson 11, which
//I suggest you read.(Note that chars basically convert their ASCII numb
ers into the
//appropriate printable characters. 65='A' for example.
count++; //I don't think it should read forever, right?
}
fclose(afile); //A surprise(don't worry, just use it to close a
file when done).
//Just put in the pointer to the
stream(the FILE thingy)
}
This program is fairly simple, and it does not take advantage of many of
C's more useful
file operations. Note though, that it is going to print out only a few characte
rs. What if you wanted to print the entire file out, though? Well, that is whe
re a thing called the EOF(end-of-file) comes into play. It is essentially a nul
l that will signal the end of the file has been reached.
So, how would you make a program to use this? Well, fgetc retrieves a c
haracter from the
file, and it will return the EOF when it reaches the end of the file. Now, it i
s possible to use a loop that will check to see if the last character is equal t
o the EOF. For example, CHARACTERREAD!=EOF. This would return true if the CHAR
ACTERREAD is not the EOF.
Here's how I would do it:
#include <iostream.h> //For cout
#include <stdio.h> //For all file i/o functions
void main()
{
FILE *afile; //We need to define a FILE type to open a file
afile=fopen("c:/AUTOEXEC.BAT", "r"); //Opens autoexec.bat, only to read, not w
rite it. afile
//is
now the stream pointing to the file autoexec.bat,
//and
is used to do operations with autoexec.bat
char c; //Without a character to store the information the program won't wo
rk
while(c!=EOF) //Checking to see if the character just read is the end of the fi
le
{
c=fgetc(afile); //This reads in the character
//Note that it is not necessary to typecast the fgetc return, as it is automa
tically turned
//into a printable character when char c is a character.
cout<<c; //The prints out the character(as you SHOULD know!)
}
fclose(afile); //Just to be safe, close the file!
}
Ok, so you finally got it to print out! Well, what is the next thing to
do? Why not have
a program to make a backup of autoexec.bat? There is a new function that you wi
ll need to add to your repetoire before this can be done. The new function is f
putc, defined in stdio.h. int futc(int c, FILE *filethinghere);. Basically, it
will return the character given to it, or it will return an EOF. It accepts a
character as the first argument, and a pointer to a stream(the FILE thing) as th
e second argument. Here is an example of how to use it:
fputc('A', newfile); //Writes the character 'A' to the file pointed to by newfil
e
However, don't forget that this does not always work. The file the stre
am points to has to
have been opened for writing, not just reading. Usually you will want to append
to a file, but in the case of our next example we want to create a new file, an
d overwrite an old one.
Now that we have a function to print to a file, why not finish up with o
ne program to
backup autoexec.bat. Basically, we will use the same loop as in the first funct
ion, that is, checking to see if the end of the file is reached, otherwise it wi
ll continue to print out characters. This time however, it will not print the c
haracters to the screen. Instead, it will print the characters to another file(
In the example, backup.aut).
--------------------------------------------------------------------------------
---------------
WARNING: If you currently have a file called backup.aut you will have it overwri
tten! DO NOT run the example program if you have the file backup.aut in the dir
ectory with your compiler! Otherwise, you will hae it overwritten.
--------------------------------------------------------------------------------
---------------
#include <stdio.h> //Needed for file i/o functions(including fopen!)
void main()
{
FILE *autoexec, *backup; //There are two files this time, the AUTOEXEC.BAT and
the backup
// file
autoexec=fopen("c:\AUTOEXEC.BAT", "r");//Open autoexec.bat to read the file
backup=fopen("backup.aut", "w"); //Create(or overwrite)backup.aut for writing
char c; //We need a buffer for reading in the charactesr
while(c!=EOF) //Just checking to see if it's the end of the file
{
c=fgetc(autoexec); //Reading in a character from autoexec.bat
fputc(c, backup); //Writing a character to the backup file!
}
fclose(autoexec);
fclose(backup); //Closing the files to finish it all up!
}
Wow! It's a program that could be useful. Feel free to use it anytime
you like. Just
remember how it works. Don't think this is the end of the file i/o information.
There is more, but for now this should be enough to whet your appetite. Oh, a
nd you case use fputc to write user input to a file also! I think you can figur
e it out!
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri
c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 11: Typcasting


Admitedly, typecasting is not a huge part of C or C++ programming. Howe
ver, there are times
when it is actually the best, or perhaps only, way to accomplish something. Typ
ecasting is
basically turning a variable of one type, say an int, into another type, a char,
for one a single
application.
Typecasts look like a data-type, like int, in between two parentheses. (
char)aninteger will
interpreted as a character for purposes of the function.
For example:
#include <iostream.h> //For cout
void main()
{
cout<<(char)65; //The (char) is a type cast, telling the computer to interpret
the 64 as a
//character, not as a number. It is going to give the ASCII output of the
//equivalent of the number 64(It should be the letter A).
}
One use of typecasting is when you want to use the ASCII characters. Fo
r example, what if
you want to create your own chart of all 255 ASCII characters. To do this, you
will need to use
a typecast to allow you to print out the integer as a character.
#include <iostream.h>
#include <conio.h>
void main()
{
for(int x=1; x<256; x++) //The ASCII character set is from 1 to 255
{
cout<<x<<". "<<(char)x<<" "; //Note the use of the int version of x to outpu
t a number
//and the use of (char) to typecast the x into a
character
//which outputs the ASCII character that corres
ponds to the
//current number
}
getch();
}
You can make a version of this program that will allow the user to enter
a number, and the
program could give the user the character corresponding to the number.
Typecasting is more useful than this, but this was just an introduction.
Admittedly, not
the most advanced lesson, but one that can be very useful none-the-less.
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentri
c.net. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)
Lesson 12: Introduction
to Classes
C++ is a bunch of small additions to C, and one major addition. This on
e addition is the
object oriented approach. As its name suggests, this deals with objects. Of co
urse, these are
not real-life objects. Instead, this objects are the essential definitions of r
eal world
objects, or people. Structures are one step away from these objects, they do no
t possess one
element of them: functions. The definition of these objects are called classes.
The easiest
way to think about a class is to imagine a structure that has functions.
What is this mysterious structure? Well, it is not only a collection of
variables under
one heading, but it is a collection of functions under that same heading. If th
e structure is
a house, then the functions will be the doors. They usually will be the only wa
y to modify the
variables in this structure, and they are usually the only to to access the vari
ables in this
structure.
From now on, we shall call these structures with functions classes(I gue
ss Marx would not
like C++). The syntax for these classes is simple. First, you put the keyword
'class' then
the name of the class. Our example will use the name computer. Then you put th
e different
variables you want the class to hold. In our example, there will be only one, p
rocessor speed.
However, before putting down the different variable, it is necessary to put the
degree of
restriction on the variable. There are three levels of restriction. The first
is public, the
second protected, and the third private. For now, all you need to know is that
the public
specifier allows any part of the program, including what is not part of the clas
s, access the
variables specified as public. The private specifier allows only the functions
of the class
that owns (not a technical term) the variable to access that variable.
#include <iostream.h>
class computer //Standard way of defining the class
{
private: //This means that all the variables under this, until a new type of re
striction is
//placed, will only be accessible to functions that are part o
f this class.
//NOTE: That is a colon, NOT a semicolon...
int processorspeed;
public: //This means that all of the functions below this(and variables, if the
re were any)
//are accessible to the rest of the program.
//NOTE: That is a colon, NOT a semicolon...
void setspeed(int p); //These two functions will be defined outside the class
int readspeed();
}; //Don't forget the trailing semi-colo
n
void computer::setspeed(int p) //To define a function outside put the name of th
e function
//after the return ty
pe and then two colons, and then the name
//of the function.
{
processorspeed = p;
}
int computer::readspeed() //The two colons simply tell the compiler that the fu
nction is part
//of the class
{
return processorspeed;
}
void main()
{
computer compute; //To create an 'instance' of the function, simply treat it
like you would
//a structure. (An instance is simply
when you create an actual object
//from the class, as opposed to having
the definition of the class)
compute.setspeed(100); //To call functions in the class, you put the name of
the instance,
//and then the function name.
cout<<compute.readspeed(); //See above note.
}
As you can see, this is a rather simple concept. However, it is very powerful.
It makes it
easy to prevent variables that are contained(or owned) by the class being overwr
itten
accidentally. It also allows a totally different way of viewing programming. H
owever, I want
to end this tutorial as an introduction. I am going to be writing more tutorial
s on classes,
which will go into more details on classes.
PLEASE send comments on this tutorial. It was written much after all the others
had been
written, and I am want to ensure that I am upholding the standard of the previou
s tutorials. I
want to be certain this tutorial is clear.
Note: My homepage is http://www.cprogramming.com. My email is webmaster@cprogra
mming.com. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)

Lesson 13: More


on Functions
The reason I have placed this tutorial at the end of the list, rather th
an as an addition to
my other lesson is simple, I don't want people who already read that tutorial to
miss this!
In lesson 4 you were given the basic information on tutorials. However,
I left out two items
of interest. First, when you declare a function you don't have to prototype it!
However, you must
give the function definition physically before you call the function. You simpl
y type in the entire
definition of the function where you would normally put the prototype.
For example:
#include <iostream.h>
void function(void) //Normally this would be the prototype. Don't forget to ex
clude the semicolon
//Only prototypes have semicolons
{
cout<<"HA! NO PROTOTYPE!";
}
void main()
{
function(); //It works like a normal function now.
}

The other programming concept is the inline function. Inline functions are not
very important,
but it is good to understand them. The basic idea is to save time at a cost in
space.
How does an inline function make the program go faster? How does it mak
e the program larger?
Does this remind you of relativity? Inline functions are really a lot like a pl
aceholder. Once
you define an inline function,using the 'inline' keyword, whenever you call that
function the
compiler will replace the function call with the actual code from the function.
How does this
make the program go faster? Simple, function calls are simply more time consumi
ng than writing
all of the code without functions. However, to go through your program and repl
ace a function
you have used 100 times with the code from the function would be time consuming.
Of course, by
using the inline function to replace the function calls with code you will also
greatly increase
the size of your program.
Using the inline keyword is simple, just put it before the name of a fun
ction. Then, when
you use that function, just pretend it is a non-inline function. For example:
#include <iostream.h>
inline void hello(void) //Just use the inline keyword before the function
{ //Note that this is a non-prototyed
function
cout<<"hello";
}
void main()
{
hello(); //Call it like a normal function...
}
However, once the program is compiled, the call to hello(); will be repl
aced by the code
making up the function.
A WORD OF WARNING: Inline functions are very good for saving time, but i
f you use them too often
or with large functions you will have a tremendously large program. Sometimes
large programs are
actually less efficient, and therefore they will run slower than before. Inline
functions are best
for small functions that are called often.
In the future we will discuss inline functions in terms of C++ classes.
However, now that
you understand the concept I will feel comfortable using inline functions in lat
er tutorials.
At this point I do not wish to add something about classes that individuals coul
d easily miss if
they did not realize that the information was in the tutorial.
Note: My homepage is http://www.cprogramming.com. My email is webmaster@cprogra
mming.com. Please
email me with comments and or suggestions. If you want to use this on your own
site please
email me and add a link to http://www.cprogramming.com. Thanks :)


Anda mungkin juga menyukai