Learning C: lesson I Hello, this is Alexander. I am writing this for those people who want to learn how to program in C, but are scared of it. It is scary, but it is not hard, well, it is hard, but it is a great feeling making a game, or a program of no value, but knowing that YOU made it. This is for the same reason that I code my own HTML, even with so many different ways to use a editor. I like to know that I made it, that I didn't just say what I wanted. If you want this sense of accomplishment, then read on. C is a programming language, of course. It is a programming language of many different dialects, just like each language that is spoken has many dialects. In C though, they are not because the 'speakers' live in the North, South, or grew 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 DJGPP. You can download DJGPP from one of the pages connected to my site and go to the programming part, or you may have another compiler. I also hope to upload the shareware version of Turbo C++, which is very similar to Borland C++. Each of these compilers is a little different. The library functions of one will have all of ANSI C, the standard, but will have many other functions, or to continue my analogy, 'words'. What I am getting at is that some of the stuff I use in this may have to be changed. If I say #include "malloc.h", you have need to say #include "alloc.h". It is because there are so many different ways of 'saying' something that sometimes it is hard to communicate, take a Southerner, and a Northerner. There are often words that get confused. So, anyway, if you don't have a compiler, I strongly suggest you get one, a simple one is good enough for my lessons, if they are worthy of that title ;), but get one. C is a different breed of programming. It has only 33 keywords for DOS, and it has no keywords to use for output. This means that almost everything is stored in a -header file-(note: all terms of interest will be set off, but I can't bold). This gives the use of many functions. But lets see a real program... #include void main() { cout<<"HEY, you, I'm alive!"; } So, that sure looks easy doesn't it. Some of the stuff is weird. Okay, lets break it down. The -#include- is a preprocessor directive, one that tells the compiler to put all the stuff in the header file -iostream.h- into our program! This allows me to use some functions later on. Also, for most header files you can also use " " to surround the name instead of <>. The next thing is -void main()- what this is saying is that I am going to have a function called -main-, and that it returns no value, hence -void-. Then those little -{- braces are used. They are like the BEGIN and END commands of pascal. basically they are used to define aresa of some function, or other things we will learn of later. The next thing is strange. If you have programmed in other languages you might think that print would be used to display text. It can be, but only if you use a function called -printf("text goes here");- the cout command can be used to display text but it needs those strange << things known as insertion operators, basically use it to put text on the screen. The quotes tell it to put the string as-is on the screen. After that, the little -;- is used to tell it that that is the end of that function. After, the braces close off the function. Pretty simple, eh? You can try out this program if you want, just cut and paste it. You should also know comments. To comment you can either use // which goes to the end of the line, or you can sue the /* and then */ to make a comment. This is useful. Make sure that you know how to use it, or you might accidentally comment out a huge chunk of code! You may be thinking by now that that is fine and good, but what If I want INPUT!? That is pretty easy. Remember cout<>. This simply is used to get input. #include void main() { int thisisanumber; cout<<"Please enter a number:"; cin>>thisisanumber; cout<> and int. int is basically a keyword that declares a variable to be an integer. Other types include char, unsigned char, float, long, double. These define characters, floating point decimals, long integers, and double floats, which go out farther. These will be used in other programs. The cin>> basically says that it should put in thisisanumber whatever the user types in. If it is not a number, the next output will be kind of weird. Then cout<< uses no quotes to print a variable, this means to print a variable, if it was as-is in quotes then it would print on the screen a string "thisisanumber". Don't forget to end functions and declarations with the semi-color(;). Otherwise you will get an error. They can be very tough to track down too. Now is about the time to learn something about variables. I have talked about declaring them, but what good is that if you don't know how to use them. Here goes: *, -, +, /, =, ==, are all operators used on numbers, these are the simple ones, if you want ore info on any of this, by the way, e-mail me at lallain@concentric.net. The * multiplies, the - subtracts, the +( adds, the = assigns the value on the right to the one on the left: a=3 means that 3 will slide over to be the value stored in a. The == is a comparison checker. a=3; a==3; This gives a the value of 3, and then sees if it has the value of three. This could be use in an if statement. DONT FORGET TO DECLARE VARIABLES. two otehr things used as comparisons are the < and > they do what they do in school check to see if it is great than or less than. To see something like greater or equal too then use >=. This is useful in some stuff I will cover next week. Learning C: lesson 2 Hello, this is Alexander. Since I finally got an email from someone who liked my previous lesson, I am going to make the second installment. This one will be about variables, and stuff like 'if' statements. 'IF' is the most important word in programming for many programs. Without it there 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 understand stuff like OR NOT etc. This are the most important, so I will describe how to use 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 is 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 this 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 characters. 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, either 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 can email me at lallain@concentric.net. A. !(1 || 0) ANSWER: 0 B. !(1 || 1 && 0) ANSWER: 0 (AND is evaluated before OR) C. !((1 || 0) && 0) ANSWER: 1 (Parenthesis are useful) 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 statements. 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 //For output #include //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 didn't need too. I think you should probably be able to make your own if statements with them without having to worry too much about problems. As always, you can email me at lallain@concentric.net 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 sounds 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 understand 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 their 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 the layout can be changed somewhat. Basically, the variable initialization allows you to either declare a variable and give it a value, or give a value to another variable. Second, the conditional statement. What it does is it says that while the conditional is true 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 //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 the loops { cout< //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<> 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 you are right! If there were only a few functions then C/C++ would not be useful. However, 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 posting 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 clear 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, there are a few specialized, but very useful funcitons, the thing is, you don't really need to use them all the time! If you have a problem with a function that you need, and I have not put 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 show you how to make your own functions! Wow, I can do that? Of course, otherwise C/C++ would 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 learn how to make our own programs. #include #include 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< 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, and then at the bottom the function is defined, and it only does one thing...outputs "This is 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 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. Functions are very useful, and I hope I explained them well enough for you to understand. 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 statements, 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 the 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 easily used than if statements. Here is an example program: #include #include 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 functions... 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 statements. Also, the reason exit works with a break is that after you break out of the switch 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 not prototype the functions, but it was a very simple example. You could easily make a few small functions. 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, why 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 importantly, you will see them a lot in other people's code. You may not need to use them much, 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 what 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 jar. In the other jar is the value of an integer. The jars are memory locations. The jar that 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 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 code. The integer is called x. Then a pointer to an integer is defined as pointer. The astrick(*) symbol means that it is a pointer. Then I give the memory location of x to pointer 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 * gives 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. Lesson 7: Structures Welcome to the seventh lesson. This is my first lesson that I will explain classes. 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: 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 one character all called under the same name. They are used like strings. I will do my next lesson on arrays, I promise, because they are very important. The struct database 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 defining 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 lesson 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 union is declared the compiler allocates enough memory for the largest data-type in the union. To access the union you use the . like in structures. Also, if you are accessing the union of structure through a pointer use the -> operator. for example, database->employee . 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. Personally, I have never used a union. Lesson 8: Array basics This is the eight installment of my lessons, and it is on arrays. Arrays are essentially 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 that 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 could 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 header 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 can easily use this to store information about some kind of game, or write something like tic-tac-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 confusing to visualize. Now, arrays are basically treated like any other variable. You can modify one value in it by putting: arrayname[arrayindexnumber]=whatever; You will find lots of useful things to do with arrays, from store information about 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 void main() { int x, y, anarray[8][8];//declares an array like a chessboard for(x=0; x<9; x++) { for(y=0; y<9; y++) { anarray[x][y]=0;//sets all members to zero once loops is done } } for(x=0; x<9;x++) { for(y=0; y<9; y++) { cout<<"anarray["<> 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 //For gets #include //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: "< //For cout #include //For many of the string functions #include //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."< //For cout #include //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 while(count<10) { cout< //For cout #include //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 cout< //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.cprogramming.com. My email is lallain@concentric.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 :)