Lesson Requirements
Nothing.
Lesson Summary
This first Lesson is aimed at introducing the complete novice to programming. Absolutely no prior knowledge is required. If you are a moderate or experienced programmer you might want to jump ahead to Lesson 2.
Programs. What Are They?
To begin we will consider some very basic but important questions:
1. What is a Program?
Now let's answer these questions:
1. A Program is a series of instructions describing the process to complete an action. Let's consider an example, how do we make a cup of coffee? We are going to write out a Program to do this:
a. Boil some water
2. You can make a Program in English -- just like the how to make coffee Program above. You make a Computer Program by writing the instructions in a Language that the computer can understand. These languages are referred to as Programming Languages.
3. Programming is a term used to describe writing Computer Programs. "Coding" and "Writing code" are other such terms.
4. Programming Languages are the instruction sets we use to describe our "recipe" (or Program) to the computer. Some common Programming Languages are BASIC, Pascal, and C. Programming Languages are discussed in more detail in Lesson 3.
Hopefully the task of programming seems a little less daunting now!
Lesson Requirements
Nothing.
Lesson Summary
The second Lesson in this Introduction to Programming Tutorial details some common terms and methods that Programmers use in the world of Programming.
Hurry Up and Decide!
Conditional statements allow us to decide whether or not to perform certain parts of the Program. We decide this by using a condition. For example, when we make coffee we only put in sugar IF the assumption "I like sugar in my coffee" is TRUE.
Stop Repeating Yourself
Loops allow us to repeat a specified task a certain number of times. For example, let's use our making coffee Program: We want to add x spoonful's of sugar to our coffee, where x is a number.
Alternatively, we keep adding sugar WHILE the number of spoonful's added so far is less than the number we require.
Conditions and Loops are very important aspects of Programming. They both form the backbone of controlling how the Program behaves -- that is, they control the "program flow".
Lesson Requirements
Nothing.
Lesson Summary
As discussed in Lesson 1, we write programs in Programming Languages. You may have heard of some of them, eg BASIC, Pascal, and C. Each programming language has it's own set of instructions. Some languages are very similar, for example there are many languages based upon C.
Here is some code from a BASIC program:
Here is some code from a Pascal program:
begin
��printf("Please enter your name: ");
Lesson Requirements
A C compiler.
Lesson Summary
The best way to learn to Program is to start doing it, so here we go!
Hello, Quake World!
In a somewhat less than radical break from the norm we will create our first program "Hello, Quake World!". This will be a simple command-line (eg DOS, Unix) program which prints "Hello, Quake World!" at the prompt.
The first thing we do is start LCCWin32.
Now create a hello.c file and enter this code:
int main(int argc, char *argv[])
prompt:\
The Break-Down
Let's have a good look at what our first program does.
From the Introduction to Programming Tutorial Lesson 1, you will remember our Program to make a cup of coffee:
a. Boil some water
Functions will be discussed in more detail in a further Lesson. For now, a basic Function looks like:
printf is another Function to print (display) characters to the screen. It takes the "Hello, Quake World!\n" parameter as the characters to display. The "Hello, Quake World!" part should be quite straight-forward as that is what is printed. The "\n" however is a special character -- the New Line character. It forces a line break.
Phew! That should be enough for your first Program! Have a good play about with it to change the text it displays. As an exercise, why don't you try to get your Program to display:
Lesson Requirements
A C compiler.
Lesson Summary
This is going to be big so you might want to do it in parts. This Lesson describes much of the "backbone" of the C language.
Types
Types define what sort of data a variable can hold; C supports several types but we will only consider two to begin with.
In our programs we will often want to store some form of data (information). We have two ways of doing this -- use a constant or use a variable. Constants are, by their definition, constant, meaning when we write the program we set their value and it never changes.
Typical data we would use a constant for is the number of seconds in a minute. However we might want to store data that we will want to change, such as the number of seconds the program has been running. We use variables in this case. Variables are declared as:
Loop Constructs
There are several different loops, but we shall start with the For loop to begin with. For loops are defined as:
At this point, let's consider some of the answers you may have come up with for Lesson 1's Exercise. You might have come up with:
int main(int argc, char *argv[])
int main(int argc, char *argv[])
int main(int argc, char *argv[])
��for(i = 1; i =< 1000; i = i + 1)
You might wonder why this variable is called "i", when previously it was stated that variables should be named meaninfully. However, we should note here that "i" is an acceptable variable name in this case because it is traditionally used as a loop counter.
Also, let us note that we have now passed two parameters to the printf() function -- the string, and the variable.
Now let's look at the While loop. As explained earlier, the While loop lets us execute a piece of code while a boolean expression is true. For example:
Note that we are initally setting i to be 1. But the loop is only going to go up to 999 because the while statement checks if the i variable is smaller than 1000.
Conditional Statements
Let's take a break from Loops and move on to conditions. The "if" condition has this form:
We've covered quite a lot in this Lesson, and don't be worried if you don't grasp all of it (or any!). We will be revisiting Loops and Conditions in the future. If you feel in the mood, here are some exercises to do:
Exercises
1. Write a function or program to determine the maximum of 3 different numbers.
Lesson Requirements
A C compiler.
Lesson Summary
Now it's time to really get into C, and in particular, a concept that many people find quite hard to understand -- Strings. Let's take things slowly, and don't worry if you can't understand all of it at first.
What is a String?
A string is a series of characters, such as "Hello, Quake World!" from our C Tutorial: Lesson 1. Now for something that upsets a lot of programmers moving to C -- C doesn't have a String type! So how do we deal with strings in C?
In short, pretty much the same way that other programming languages deal with strings, except in C we get to see the inside-workings. A string is merely a list (or array) of characters. Here is how we represent strings in C:
Input / Output
In this Lesson we are going to look at the Console I/O -- eg, reading and writing text to the DOS prompt. First of all, consider the term "Input / Output". In other words, reading text from the keyboard, and putting text onto the screen.
Here are two typical I/O functions which are defined in C's standard I/O Library functions (remember the "stdio.h" file?):
printf()
printf() is defined as:
The formatting string can contain various formatting symbols. So far we have seen "%d" to print an integer, "%s" for a string, and "%c" for a character. There are also control codes such as "\n" for a new line. Perhaps you should consult a good C reference manual along with this course to learn about the other symbols.
printf()
scanf() is defined as:
Example()
Let's write a simple program to ask for the user's name and age.
int main(int argc, char *argv[])
scanf("%40s", name); -- This line means we want to read in a string of maximum 40 characters, as we have only allocated memory for that number in our string (char *name[40];).
scanf("%d", &age); -- Do you notice the "&" in front of the variable name? This allows us to change its value (much akin to a var parameter in pascal). The "&" character will be explained in more detail in a later tutorial.
That about wraps up this tutorial. In the next tutorial we'll bring together some of the things we've learned. In the meantime, why don't you try this exercise:
1. Read in a list of 10 integers from the console, and print out the largest.
Till next time!
Lesson Requirements
A C compiler.
Lesson Summary
Moving on from Lesson 3: Strings and I/O, we come to an interesting topic called Pointers.
But First!
Before we start, let's cover a solution to the last exercise. If you recall, the exercise was to read 10 integers from the console, and print out the largest. Here is one way you might have solved this:
int Max(int a, int b)
int main(int argc, char *argv[])
��printf("Please input your 10 numbers, in the form: 1 2 3 4...\n");
��/* Now find the maximum number */
��/* Print out the maximum number */
Now would be a good time to go back over the entire series of tutorials and make sure you understand them.
Pointers
All the information we store in a computer is stored in it's memory, and we need a way of keeping track of where this information is stored. The way we do this is by using Pointers. Pointers are essentially variables which "point" to another variable (a location in memory, i.e. the 64th byte). You could think of Pointers as being similar to your house number on the street you live in.
How do we declare a pointer? A pointer variable is declared as:
NOTE: Initially the pointer may not be setup (i.e. it could point to anything). More importantly, we have only allocated memory for the pointer, and not for the character we wish it to point to. We allocate that memory using the function malloc(), which is prototyped as:
This example uses a pointer to an integer:
// allocate memory
// set the value of the memory location pointed to by myint:
Finally, we use "*" to access the memory that the pointer is pointing to.
Well that's all for this Lesson. It is recommended that you read more on Pointers in a good C reference book.
Lesson Requirements
A C compiler.
Lesson Summary
Structures and their uses.
But First!
Sometimes we want to store more data about an object than we can use by a basic type (i.e. an int, char, etc). Or we might wish to group together a set of attributes for an object. For example, in Quake we might wish to store information on the player(s) in a game. Each player would have the following attributes: Name, Health, Location, and so on.
We could store this information in a set of variables:
A better solution would be to have an array of a new data type, or structure, called "player". This is where structures become useful. A structure allows us to declare a new data type called "player" which has members (the attributes for the player): name, health, and location. So what does the code look like?
We could now declare a variable for player_one using this new structure, "player", as:
We need a way of accessing the members, or attributes, of the structure. We do this by using the "." (period) operator. For example, if we wanted to access the name of the player in the fourth array position:
November 27 / 1997
Programming Tutorial - Lesson 1: An Introduction to Programs
2. How do I make Programs?
2. What is "Programming"?
4. What is a Programming Language?
Making Coffee:
Well, nothing Earth-shattering here. But the point is that a Program is nothing more than a set of instructions. A computer program is just like the above recipe to make coffee.
b. Get an empty mug
c. Place a spoonful of coffee in the mug
d. When the water has boiled, fill the mug with the water
e. If we want milk, add milk to taste
f. If we want sugar, add sugar to taste
let myname$ = "James"
print "What is your name?"
input yourname$
print "Hello, ";yourname$;" it's nice to meet you."
print "My name is ";myname$
var
And here is some code from a C program:
��yourname : string[30];
��writeln('Please enter your name:');
��readln(yourname);
��writeln;
��writeln('Hi', yourname, ' my name is James.');
end.
{
Don't worry about all these strange words. The important thing to note is that different programming languages have different instructions. We will be looking at the C and C++ languages in greater detail in the next Tutorials.
��char yourname[30];
��scanf("%s", yourname);
}
#include <stdio.h>
Now compile and run your program. Assuming you have no errors, you will receive this output:
{
��printf("Hello, Quake World!\n");
}
prompt:\hello.exe
If you do have errors when compiling your code, go over it again and look for errors.
Hello, Quake World!
#include <stdio.h>
The '#' (hash symbol) defines the line as an Instruction for the PreProcessor. The instruction is to include the file "stdio.h" in our source file. Essentially, the PreProcessor replaces this #include <stdio.h> line with the contents of the file "stdio.h". This is basically a merge, like you get in a Word Processor. So now you are probably wondering what this "stdio.h" file is. Well that's not important right now.
int main(int argc, char *argv[])
This is a Function declaration. Functions allow us to group together pieces of code and refer to them in a simpler and more structured way. Instead of having thousands of lines of code all together, we group them seperately into modules that we can then call individually.
Making Coffee:
Let's say we want to make 12 cups of coffee. We could repeat the instructions of the above recipe (or Program) 12 times. Or, if we grouped the instructions into a Function, we could call this Function 12 times from the one Program -- the program to "Make 12 cups of coffee".
b. Get an empty mug
c. Place a spoonful of coffee in the mug
d. When the water has boiled, fill the mug with the water
e. If we want milk, add milk to taste
f. If we want sugar, add sugar to taste
return_type function_name (arguments)
So let's get back to our code:
{
��...
��function_body
��...
}
int main(int argc, char *argv[])
This declares a Function called "main()" which returns an integer value (a number). The Function takes two arguements, which we wont worry about just yet. Typically, all console (DOS, Unix) programs require a main() Function declared.
{
So what does this bit of code do? The first thing you might notice is the { } brackets. These brackets group pieces of code together, and in this case they are used to group the code to the main() Function.
��printf("Hello, Quake World!\n");
}
Welcome to my first program.
A few solutions to this exercise will be provided in the next Lesson.
This is line number 2.
And this is line number 3.
by: John Crickett & Neil Henderson
Posted: November 27 / 1997
int - A integer number eg 0, 1, -4, 7, 11931
Variables
char - A character eg 'a', 'b', 'c', 'r', 'z'
<type> <variable_name>;
For example:
int num_of_seconds;
This creates a variable called num_of_seconds, of type int (integer). Variable names can be anything begining with an alphabetical character and continuing in any combination of alphanumeric characters. You can't use a restricted name as a variable (eg a function or keyword). A good programming procedure is to use meaningful variable names instead of just random names. This means it is much easier to read your code, or for other people to read it.
for (start condition; boolean test; action)
The start condition is a typically an assignment operation such as:
{
��...
��code
��...
}
i = 1;
which sets the variable i to have the value of 1. The next statement is a boolean condition such as:
i < 5;
A boolean value is either TRUE or FALSE. In this case the variable i can either store a value less than 5 or not. Finally we have the action statement -- typically we use For loops to perform a piece of code a set number of times. The action statement allows us to determine the "step size".
#include <stdio.h>
or possibly:
{
��printf("Hello this is my first program.\nThis is line ��number 2.\nAnd this is line number 3.\n");
}
#include <stdio.h>
Both of these are correct answers. But let's consider that the Exercise asked you to print 1000 line numbers. This is where loops come in handy, and here's an example to do that:
{
��printf("Hello this is my first program.\n");
��printf("This is line number 2.\n");
��printf("And this is line number 3.\n");
}
#include <stdio.h>
Ok theres some news things in this. Firstly the "%d" has been introduced in the printf statement. Furtheremore, there is a comma followed by the variable i -- ", i".
{
��int i;
��{
����printf("This is line number: %d\n", i);
��}
}
while I am alive
In C, While loops typically take the form:
��breathe
while (boolean_expression)
Let's go back to the 1000 line number problem, and this time use a While loop to solve it:
{
��...
��code-body
��...
}
#include <stdio.h>
Now let's break this new code down:
int main(int argc, char *argv[])
{
��int i;
��i = 1;
��while(i < 1000)
��{
����printf("This is line number: %d\n", i);
����i = i + 1;
��}
}
(i < 1000)
This is a boolean expression (i.e. it is either TRUE or FALSE) which evaluates the the expression "is i less than 1000?". This brings us to an interesting point -- it is very common to either repeat the loop too few times, or worse too many times when using while loops. So be very careful with them. Can you see the deliberate error above?
if (boolean_expression) then
There is also an Else statement we can use:
��do-this-code
if (boolean_expression) then
Note that C does not use "then" in it's language. Here is an example:
��do-this-code
else
��do-something-else
int Max(int a, int b)
This function returns the greater of two integer values.
{
��if (a > b)
��{
����return a;
��}
��else
��{
����return b;
��}
}
2. Write a program to print out all the numbers from 1000 down to 1.
by: John Crickett & Neil Henderson
Posted: November 27 / 1997
char mystring[20];
This creates an array of 20 characters called "mystring". Now that we have an idea of how to represent strings, let's move onto Input / Output and then some example programs.
printf()
These two functions are defined in a standard C Library (ie, someone has already written them for us). When we link our program, we include the Library for printf() and scanf(). At this point you might wonder how the compiler knows what printf() and scanf() take as parameters, etc. All of the standard functions are prototyped in header files (.h files), and the file "stdio.h" contains the prototypes for the standard I/O functions. You may notice that "stdio" is an abbreviation for "standard input output".
scanf()
int printf( const char *format [, argument]... );
What does this mean? Well, printf() is a function which returns an integer (either the number of characters printed, or a negative value if it failed). Its first arguement is a string representing the formatting, followed by an optional number of variables to be substitued into the format string.
int scanf( const char *format [,argument]... );
This is the reverse of printf() -- instead of printing formatted text, it reads formatted text from the Console (keyboard). It returns the number of variables it successfully retrieved.
#include <stdio.h>
Some points to notice here:
{
��char *name[40];
��int age;
��printf("What is your name?\n");
��scanf("%40s", name);
��printf("How old are you %s?\n", name);
��scanf("%d", &age);
��printf("So %s, you are %d years old and you're writing C.\n", ��name, age);
}
by: John Crickett & Neil Henderson
Posted: January 8 / 1997
#include
There isn't anything new here, however from now on we shall replace "i = i + 1" with the post increment operator "++" (i.e. "i++"). In C this means exactly the same as "i = i + 1". In this case we want to use the "post" increment (i.e. add one to i, after each iteration of the loop has finished. This is opposed to the "pre" increment operator, which adds one before the iteration).
{
��if (a > b)
����return a;
��else
����return b;
}
{
��int num[10];
��int largest_so_far;
��int i;
��scanf("%d %d %d %d %d %d %d %d %d %d", &num[0], &num[1], &num[2], &num[3], &num[4], &num[5], &num[6], &num[7], &num[8], &num[9]);
��largest_so_far = num[0];
��for (i = 1; i < 10; i = i + 1)
��{
����largest_so_far = Max(largest_so_far, num[i]);
��}
��printf("Largest Number was: %d", largest_so_far);
}
var_type *var_name;
which declares a variable called 'var_name' of type 'var_type'. For example:
char *mychar;
declares a pointer to a character.
void *malloc(int size);
We have introduced a new type called "void", which essentially means it doesn't have a type. We'll return to this later. The malloc() function allows us to allocate memory as we need it (i.e. dynamic memory allocation). The parameter "size" allows us to specifiy the amount of memory we wish to allocate -- a point to the beginning of the block is returned.
// NOTE: This is a simplified version!
// declare variable
Some new things here: Firstly the "(int *)" is used before the malloc(). This is known as a typecast, which essentially is telling the compiler what type the malloc() is going to return (in this case it is a pointer to an integer). "sizeof(int)" is the parameter being used, and is simpler for portablility and for use of structures which we shall cover at a later stage.
int *myint;
myint = (int *) malloc(sizeof(int));
*myint = 1;
by: John Crickett & Neil Henderson
Posted: January 8 / 1998
player_name
However, let's say we have a second player. We would have to create a copy of these variables, slightly renamed, for the second player:
player_health
player_location
player2_name
And what if there are ten players? We would need thirty variables to hold all of the attributes for these ten players. There are obvious reasons why this is not the best solution, and also some other reasons that we will go into later.
player2_health
player2_location
struct player
NOTE: The location would actually be a Vector, but in this example we will keep things simple.
{
��char name[40];
��int health;
��int location;
};
struct player player_one;
or even better, an array of players as:
struct player players[16];
Accessing the Members of a Structure
players[3].name;
Remember, the array starts from zero! And if we wanted to set the health of Player 8 to zero:
players[7].health = 0;
Thats all for now. The sixth Lesson will deal with Structures and a new concept called Linked Lists.
This article was written by John Crickett & Neil Henderson. You can
find out more about them at quake2.com/dll.