Caribbean Secondary Education Certificate - Information Technology/Developing Algorithms to Solve Simple Problems

From WikiEducator
Jump to: navigation, search

WRITING SIMPLE PROGRAMS


The Program Example Perhaps the best way to start looking at C is to jump straight in with our first ever C program. Here it is:

  1. 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?

  1. include

The pre-processor is the part of the compiler which actually gets your program from the file. This is a pre-processor directive. It is not part of our program, it is an instruction to the compiler to make it do something. It tells the C compiler to include the contents of a file, in this case the system file stdio.h. The compiler knows it is a system file, and therefore must be looked for in a special place, by the fact that the name is enclosed in <> characters.

<stdio.h> All versions of C have exactly the same library functions. This is the name of the standard library definition file for all STanDard Input Output. Your program will almost certainly want to send stuff to the screen and read things from the keyboard. stdio.h is the name of the file in which the functions that we want to use are defined. A function is simply a chunk of program that we want to use a lot, so we stuck it in a parcel and gave it a name. The function we want to use is called printf (see later). To use printf correctly C needs to know what it looks like, i.e. what things it can work on and what value it returns. The actual code which performs the printf will be tied in later by the linker. Note that without the definition of what printf looks like the compiler makes a guess when it sees the use of it. This can lead to the call failing when the program runs, a common cause of programs crashing. The .h potion is the language extension, which denotes an include file. The <> characters around the name tell C to look in the system area for the file stdio.h. If I had given the name "robsstuff.h" instead it would tell the compiler to look in the current directory. This means that I can set up libraries of my own routines and use them in my programs, a very useful feature.

void 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.

main In this example the only function in the program is main. Larger programs are split up into lots of functions. The name of the function currently being defined. The name main is special, in that the main function is actually the one which is run when your program is used. A C program is made up of a large number of functions. Each of these is given a name by the programmer and they refer to each other as the program runs. C regards the name "main" as a special case and will run this function first. If you forget to have a main function, or mistype the name, the compiler will give you an error.

( void ) 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....

float 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.

height, width, area, wood_length 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.

scanf 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).

A parameter is something for a function to work on. This line is a call to the function scanf. The compiler knows that this is a function call by the fact that it is followed by a parameter list. (see later) What the compiler does at this point is parcel up the parameters you have given and then call scanf, passing the parameter information on. This function is expecting a particular sequence and type of parameters. 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.

"%f", 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 " character defines the limits of the string. In C a string is given as a sequence of characters enclosed in " characters. You will meet the concept of delimiters regularly in C. A delimiter is a particular character which is to be used to define the limits of something. C uses different delimiters in different places, the " character is used to delimit a string of text. When the compiler sees the first " it recognises that everything up until the next " is a sequence of characters which we wish to use. It therefore just assembles the string until it finds another ". The string must all appear on the same line, otherwise you will get an error. 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.

&height 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.

scanf ( "%f", &width ) ; The function of this line is identical to the one above, except that the result is placed into the variable called width.

area = 2 * height * 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.

wood_length = 2 * ( height + width ) * 3.25 ; When I write programs I use brackets even when the compiler does not need them. This makes the program clearer.

This is an expression much like above, this time it is important that you notice the use of parenthesis to modify the order in which values are calculated in the expression. Normally C will work out expressions in the way you would expect, i.e. all multiplication and division will be done first, followed by addition and subtraction. In the above expression I wanted to do some parts first, so I did what you would do in mathematics, I put brackets around the parts to be done first.

printf 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.

( "The area of glass needed is : %f metres.\n", 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.

area ) ; 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.

printf ( "The length of wood needed is : %f feet.\n", wood_length ) ; 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!

Punctuation 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

  1. 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 ) ;}


Reference: [1]