Introduction to C Programming by Rob Miles, Electronic Engineering
Perhaps the best way to start looking at C is to jump straight in with our first ever C program. Here it is:
#include <stdio.h>
void main ( void )
{
float height, width, area, wood_length ;
scanf ( "%f", &height ) ;
scanf ( "%f", &width ) ;
area = 2 * height * width ;
wood_length = 2 * ( height + width ) * 3.25 ;
printf ( "The area of glass is : %f metres.\n",
area ) ;
printf ( "The length of wood is : %f feet.\n",
wood_length ) ;
}You should easily work out what it does, but what do all the various bits mean?
Means literally this means nothing. In this case it is referring to the function whose name follows. It tells C that this function, which could return something interesting, (see printf) in fact returns nothing of interest whatsoever. Why do this? Because we want to be able to handle the situation where I make a mistake and try to ascribe meaning to something which has none. If the C compiler has already been told that a given entity has no meaning it can detect my mistake and produce an error.
This is a pair of brackets enclosing void. This may sound stupid, but actually tells the compiler that the function main has no parameters. A parameter to a function gives the function something to work on. When you define a function you can tell C that it works on one or more things, for example sin(x) could work on a floating point value of angle x. We will cover functions in very great detail later in this course.
This is a brace. As the name implies, braces come in packs of two, i.e. for every open brace there must be a matching close. Braces allow me to lump pieces of program together. Such a lump of program is often called a block. A block can contain the declaration of variable used within it, followed by a sequence of program statements which are executed in order. In this case the braces enclose the working parts of the function main.
When the compiler sees the matching close brace at the end it knows that it has reached the end of the function and can look for another (if any). The effects of an un-paired brace are invariably fatal....
Our program needs to remember certain values as it runs. Notably it will read in values for the width and height of the windows and then calculate and print values for the glass area and wood length. C calls the place where values are put variables. At the beginning of any block you can tell C that you want to reserve some space to hold some data values. Each item you can hold a particular kind of value. Essentially, C can handle three types of data, floating point numbers, integer number and characters (i.e. letters, digits and punctuation).
You declare some variables of a particular type by giving the type of the data, followed by a list of the names you want the variables to have. We will look at the precise rules which apply when you invent a variable name in more detail later, for now you can say that the variable must start with a letter and from then on only contain letters, numbers and the _ character.
This is a list. A list of items in C is separated by the , character. In this case it is a list of variable names. Once the compiler has seen the word float (see above) it expecting to see the name of at least one variable which is to be created. The compiler works its way down the list, creating boxes which can hold floating point values and giving them the appropriate names. From this point on we can refer to the above names, and the compiler will know that we are using that particular variable.
The semicolon marks the end of the list of variable names, and also the end of that declaration statement. All statements in C programs are separated by the ; character, this helps to keep the compiler on the right track.
The ; character is actually very important. It tells the compiler where a given statement ends. If the compiler does not find one of these where it expects to see one it will produce an error. You can equate these characters with the sprocket holes in film, they keep everything synchronised.
If you have been used to other programming languages you might expect that the printing and reading functions are part of the language. In C this is not the case, instead they are defined as standard functions which are part of the language specification, but not part of the language itself. Any decent book on C must have a big section on how to use the standard functions and what they are. The standard input/output library contains a number of functions for formatted data transfer, the two we are going to use are scanf (scan formatted) and printf (print formatted).
The compiler knows what scanf looks like and the kind of information scanf uses is expecting because it has already seen the file stdio.h, which is where this function is defined. The compiler can now check that the way we have used scanf agrees with the definition. This allows valuable checking to be carried out. If the compiler had not seen this function defined before it would simply guess what it was supposed to do and probably produce a program which would not work properly.
This marks the start of the list of parameters to the scanf function. A parameter is something which a function operates on. All functions must have a parameter list, if they have no parameters the list is empty. Note that the parameters you give when you call a function must agree in number and type with those that the function expects, otherwise unpredictable things will happen. The system file stdio.h contains a description of what scanf should be given to work on. If what you supply does not agree with this the compiler will generate an error for you.
This is the set of parameters to the call of scanf. scanf is short for scan formatted. The function is controlled by the format string, which is the first parameter to the function. The second and successive parameters are addresses into which scanf puts the values it has been told to fetch.
The scanf function has been told to look out for certain characters in the format string and treat them as special. Such a special character is %. The % character tells scanf that we are giving the format of a number which is to be processed. The letter after the % character tells scanf what kind of value is being fetched, f means floating point. This command will cause scanf to look for a floating point number on the input. If it finds one it is to put the value in the address given as the next parameter.
In C a function cannot change the value of a parameter which is supplied to it. This is quite a departure from other languages, which let you do this. It does make life more complicated, when you want your function to be able to change the value of something. The way that you get the effect is by cheating. Instead of passing scanf the variable height we have instead supplied &height. The & is very important. When the compiler sees the & it regards this as an instruction to create a pointer to the given variable, and then pass this pointer to scanf. This means that when scanf runs it is given a a pointer to where the result is to be placed, which is OK.
The ) character marks the end of the list of parameters to scanf and the ; then end of this statement.
The function of this line is identical to the one above, except that the result is placed into the variable called width.
This is an assignment. The assignments are the bread and butter of programming. A good proportion of your programs will be instructions to assign new values to variables, as the various results are calculated.
C uses the = character to make assignments happen. The first part of this statement is the name of a previously defined variable. This is followed by the = character which I call the gozzinta. I call it that because the value on the right gozzinta (goes into ) the variable on the left. When this program runs the expression is worked out and then the result is placed in the specified variable. In this case the expression works out the total amount of glass needed. This result is then placed in the area variable.
The printf function is the opposite of scanf. It takes text and values from within the program and sends it out onto the screen. Just like scanf it is common to all versions of C and just like scanf it is described in the system file stdio.h.
The first parameter to printf is the format string, which contains text, value descriptions and formatting instructions.
This is another format string. The text in this message will appear as it is given, although the delimiters will not be printed. Like scanf the % tells printf that a value description follows, the f meaning that a floating point value is to be printed. You can get quite clever with place markers, using them to specify exactly how many spaces to fill with the value and, with real numbers, how many places after the decimal point to print, for example :
%d - I want you to print the value of a signed, decimal integer
%c - I want you to print the character which responds to this value (more on characters a little later)
%f - I want you to print the value of a signed, decimal, floating point number. I want to see the result with a floating decimal point.
%5d - I want you to print the decimal integer in five character positions, right justified.
%6.2f - I want you to print the decimal floating point number in six character positions, right justified and to an accuracy of two decimal places.
The rest of the text is quite straightforward, until we get to the \ character, which marks a formatting instruction. These instructions allow you to tell printf to do things like take a new line, move the cursor to the start of the line and etc. The \ is followed by a single character which identifies the required function. In the case of our program we want to take a new line at that point, and that is what n does. Note that unlike some languages, print statements do not automatically take a new line. This means that the programmer has to do more, but does make for greater flexibility.
The next piece of information that printf needs is the name of the variable to be printed. Note that in this case we do not need to specify the address of the variable, we are just sending its value into the function so that it can be printed out.
This line is very similar to the one above it, except that the message and the variable printed are different.
This closing brace marks the end of the program. The compiler will now expect to see the end of the file or the start of another function.. If it does not, it means that you have got an unmatched brace somewhere in the program, which will almost certainly mean your program will not work properly. Not all compilers notice this!
That marks the end of our program. One of the things that you will have noticed is that there is an awful lot of punctuation in there. This is vital and must be supplied exactly as C wants it, otherwise you will get what is called a compilation error. This simply indicates that the compiler is too stupid to make sense of what you have given it!
You will quickly get used to hunting for and spotting compilation errors, one of the things you will find is that the compiler does not always detect the error where it takes place, consider the effect of missing out a "(" character. Note that just because the compiler reckons your program is OK is no guarantee of it doing what you want!
Another thing to remember is that the layout of the program does not bother the compiler, the following is just as valid
#include <stdio.h>
void main (){ float height, width, area, wood_length ; scanf ( "%f",
&height ) ; scanf ( "%f", &width ) ; area = 2 * height * width ;
wood_length = 2 * ( height + width ) * 3.25 ; printf (
"The area of glass needed is : %f metres.\n"
, area ) ; printf (
"The length of wood needed is : %f feet.\n"
, wood_length ) ;}- although if anyone writes a program which is laid out this way they will get a smart rap on the knuckles from me!
The grammar of programs is something you will pick up as we look at more and more of them....