Sunday, May 1, 2011

C++ Transparencys


C TransparencysTOC.pdf -

C Transparencys01-06.pdf -

C Transparencys07-14.pdf -

C Transparencys15-18.pdf -

C Transparencys19-23.pdf -

C++ tutorial for C users


C++ tutorial for C users


This text is aimed at C users who wish to learn C++. It is also interesting for experienced C++ users
who leaved out some features of the language. The possibilities of C++ are briefly enunciated and
illustrated. When you will try to use them for your own programs you will encounter a lot of problems
and compilation errors. Come back to this text and look carefully at the examples. Make use of the
help files of your development environment. Do not hesitate to copy the examples from this text and
paste them inside your development environment in order to test and modify them.


C tutorial for C users

Lesson 13: More on Functions


Lesson 13: More on Functions



The reason I have placed this tutorial at the end of the list, rather than 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 simply 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 exclude 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 make the program larger?

Does this remind you of relativity?  Inline functions are really a lot like a placeholder.  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 consuming than writing

all of the code without functions.  However, to go through your program and replace 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 function.  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 replaced by the code

making up the function.



A WORD OF WARNING: Inline functions are very good for saving time, but if 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 later tutorials.

At this point I do not wish to add something about classes that individuals could easily miss if

they did not realize that the information was in the tutorial.




Note: My homepage is http://www.madezee.com.  My email is webmaster@madezee.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.madezee.com.  Thanks :)


Lesson 12: Introduction to Classes


Lesson 12: Introduction to Classes

C++ is a bunch of small additions to C, and one major addition.  This one addition is the
object oriented approach.  As its name suggests, this deals with objects.  Of course, these are
not real-life objects.  Instead, this objects are the essential definitions of real world
objects, or people.  Structures are one step away from these objects, they do not 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 the structure is
a house, then the functions will be the doors.  They usually will be the only way to modify the
variables in this structure, and they are usually the only to to access the variables in this
structure.

From now on, we shall call these structures with functions classes(I guess 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 the different
variables you want the class to hold.  In our example, there will be only one, processor 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 class, 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 restriction is
   //placed, will only be accessible to functions that are part of 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 there 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-colon

void computer::setspeed(int p) //To define a function outside put the name of the function
  //after the return type 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 function 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 overwritten
accidentally.  It also allows a totally different way of viewing programming.  However, I want
to end this tutorial as an introduction.  I am going to be writing more tutorials 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 previous tutorials.  I
want to be certain this tutorial is clear.


Note: My homepage is http://www.madezee.com.  My email is webmaster@madezee.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.madezee.com.  Thanks :)

Lesson 11: Typcasting


Lesson 11: Typcasting

Admitedly, typecasting is not a huge part of C or C++ programming.  However, there are times
when it is actually the best, or perhaps only, way to accomplish something.  Typecasting 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.  For 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 output a number
//and the use of (char) to typecast the x into a character
//which outputs the ASCII character that corresponds 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.madezee.com.  My email is webmaster@madezee.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.madezee.com.  Thanks :)

Lesson 10: File I/O(part 1)


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 not cover a great
deal, for example, this lesson will not deal with searching files or reading specific data from
files.  It will merely be concerned with opening, writing, and reading text files.  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 functions 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 the 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 *fopen(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 file, and assign
 //it to newfile

Basically, fopen accepts two strings.  One of them is the file name, including the path,and
the other is what the file will be used for(the mode).  In this case, the r designates 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 autoexec.bat file with giberish is not a good idea!

For a reference here is a chart listing the different ways you open a file:

r Open for reading only.

w Creates a file for writing. If a file by that name already exists, it will be overwritten.

a Append; open for writing at the end of the file, or create the file if it 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 already 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 file.

Now, let's say you want to print the contents of autoexec.bat to your screen.  Assuming you
want to make a program to do this you would need a function for reading from a file.  There are numerous useful ones, but for now we will use int fgetc(FILE *stream)(Note that it returns an int, but the range will still be printable(so it is the same as a char), defined in iostream.h.  Basically, fgetc will get the next character from a file you give it(that is, the stream you give it).  An example would be the following code to display the first few characters of your autoexec.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 fil
  afile=fopen("c:/AUTOEXEC.BAT", "r"); //Open up the autoexec.bat file for reading
  //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 printed.

//Please note the use of (char) to 'typecast' the returned integer.  That 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 numbers 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 characters.  What if you wanted to print the entire file out, though?  Well, that is where a thing called the EOF(end-of-file) comes into play.  It is essentially a null 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 character from the
file, and it will return the EOF when it reaches the end of the file.  Now, it is possible to use a loop that will check to see if the last character is equal to the EOF.  For example, CHARACTERREAD!=EOF.  This would return true if the CHARACTERREAD 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 write 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 work
 while(c!=EOF) //Checking to see if the character just read is the end of the file
 {
   c=fgetc(afile); //This reads in the character
   //Note that it is not necessary to typecast the fgetc return, as it is automatically 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 will need to add to your repetoire before this can be done.  The new function is fputc, 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 the second argument.  Here is an example of how to use it:

fputc('A', newfile); //Writes the character 'A' to the file pointed to by newfile

However, don't forget that this does not always work.  The file the stream 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, and overwrite an old one.
Now that we have a function to print to a file, why not finish up with one program to
backup autoexec.bat.  Basically, we will use the same loop as in the first function, that is, checking to see if the end of the file is reached, otherwise it will continue to print out characters.  This time however, it will not print the characters 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 overwritten!  DO NOT run the example program if you have the file backup.aut in the directory 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, and you case use fputc to write user input to a file also!  I think you can figure it out!


Note: My homepage is http://www.madezee.com.  My email is webmaster@madezee.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.madezee.com.  Thanks :)


Lesson 9: Strings


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 words.  Like,
"This is a string".

Strings are basically character arrays.  For example, to declare a string 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 arrays begin at
0, not 1 for the index-number.  Also, a string ends with a null character, literally 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 person's name.  If you
wanted to, you would need a string, because a name can't fit in one variable!  It 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 first new-line, for
example, when a user hits enter.  Gets is in stdio.h. All you do, is put the name of the array and it will work out,
because the pointer char *s is basically one way you tell a function that you will 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 will 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 functions 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 either 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 either 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).  The 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 what 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 equal 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 outputting 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.madezee.com.  My email is webmaster@madezee.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.madezee.com.  Thanks :)