SlideShare une entreprise Scribd logo
1  sur  94
Télécharger pour lire hors ligne
Introduction to
C Programming
Rob Miles
Department of Computer Science
i
Contents
Computers 1
An Introduction to Computers........................................................................................1
Hardware and Software ....................................................................................1
Data and Information .......................................................................................2
Data Processing................................................................................................2
Programming Languages 4
What is Programming? ..................................................................................................4
From Problem to Program ................................................................................5
Programming Languages ...............................................................................................8
C 8
A look at C ....................................................................................................................8
Making C Run..................................................................................................9
Creating C Programs........................................................................................9
What Comprises a C Program?.......................................................................10
The Advantages of C......................................................................................11
The Disadvantages of C..................................................................................11
A First C Program 11
The Program Example .................................................................................................11
#include ........................................................................................................12
<stdio.h>.......................................................................................................12
void ...............................................................................................................12
main ..............................................................................................................13
( void )...........................................................................................................13
{ .....................................................................................................................13
float ...............................................................................................................13
height, width, area, wood_length................................................................13
; .....................................................................................................................14
scanf .............................................................................................................14
( .....................................................................................................................14
"%f", ..............................................................................................................14
&height..........................................................................................................15
) ;...................................................................................................................15
scanf ( "%f", &width ) ;.................................................................................15
area = 2 * height * width ;............................................................................15
wood_length = 2 * ( height + width ) * 3.25 ;.................................................16
printf..............................................................................................................16
( "The area of glass needed is : %f metres.n",.........................................16
area ) ; ..........................................................................................................17
printf ( "The length of wood needed is : %f feet.n", wood_length ) ; ......17
} .....................................................................................................................17
Punctuation ....................................................................................................17
Variables 18
ii
Variables and Data.........................................................................................18
Types of Variables .......................................................................................................18
Declaration ..................................................................................................................18
int variables....................................................................................................19
float variables ................................................................................................19
char variables ................................................................................................19
Missing Types................................................................................................19
Variable Declaration....................................................................................................19
Giving Values to Variables ..........................................................................................20
Expressions....................................................................................................21
Types of Data in Expressions..........................................................................22
Getting Values into the Program..................................................................................23
Writing a Program 24
Comments......................................................................................................24
Program Flow ..............................................................................................................24
Conditional Execution - if...............................................................................25
Conditions and Relational Operators ..............................................................26
Combining Logical Operators.........................................................................27
Lumping Code Together.................................................................................27
Magic Numbers and #define..........................................................................28
Loops .............................................................................................................29
Breaking Out of Loops ...................................................................................32
Going Back to the Top of a Loop....................................................................32
More Complicated Decisions..........................................................................33
Complete Glazing Program ............................................................................33
Operator Shorthand........................................................................................34
Statements and Values....................................................................................35
Neater Printing...............................................................................................36
Functions 37
Functions So Far..........................................................................................................37
Function Heading...........................................................................................37
Function Body................................................................................................38
return .............................................................................................................38
Calling a Function..........................................................................................38
Scope .............................................................................................................39
Variables Local to Blocks...............................................................................40
Full Functions Example..................................................................................40
Pointers........................................................................................................................42
NULL Pointers...............................................................................................44
Pointers and Functions ...................................................................................44
Static Variables............................................................................................................45
Arrays 46
Why We Need Arrays ..................................................................................................46
Sorting ...........................................................................................................47
Array Types and Sizes..................................................................................................49
More Than One Dimension............................................................................50
Switching 53
Making Multiple Decisions..........................................................................................53
Strings 55
iii
How long is a piece of string?.......................................................................................55
Putting Values into Strings ..........................................................................................56
Using Strings...............................................................................................................57
The String Library .......................................................................................................58
strcpy .............................................................................................................59
strcmp............................................................................................................59
strlen..............................................................................................................59
Reading and Printing Strings .......................................................................................59
Bomb Proof Input.........................................................................................................60
Structures 61
What is a Structure?.....................................................................................................61
How Structures Work...................................................................................................63
Pointers to structures....................................................................................................63
Defining your own Types .............................................................................................64
Files 65
When do we use Files?.................................................................................................65
Streams and Files ...........................................................................................65
fopen and fclose ...........................................................................................................66
Mode String ...................................................................................................68
File Functions ..............................................................................................................70
fread and fwrite..............................................................................................70
The End of the File and Errors.....................................................................................71
Memory 72
Fetching Memory.........................................................................................................72
malloc ............................................................................................................72
free.................................................................................................................73
The heap......................................................................................................................73
C and Large Programs 74
Building Large Programs in C .....................................................................................74
The Compile and Link Process.......................................................................74
Referring to External Items ............................................................................75
The Make Program.........................................................................................76
Projects ..........................................................................................................76
The C Pre-Processor.....................................................................................................77
The #include Directive ...................................................................................77
Conditional Compilation ................................................................................77
A Sample Project .........................................................................................................78
The Problem...................................................................................................78
The Data Structure .........................................................................................78
Program Files.................................................................................................79
The Most Important Bit!.................................................................................84
Glossary of Terms 93
Index 95
This document is © Rob Miles 2001 Department of Computer Science, The University of Hull
All rights reserved. No reproduction, copy or transmission of this publication may be made without written
permission.
iv
The author can be contacted at: The Department of Computer Science, The University of Hull,
HULL, HU6 7RX
r.s.miles@dcs.hull.ac.uk
Computers ? 1
Computers
An Introduction to Computers
Qn: Why does a bee hum?
Ans: Because it doesn't know
the words!
One way of describing a computer is as an electric box which humms. This, whilst
technically correct, can lead to significant amounts of confusion, particularly
amongst those who then try to program a fridge. A better way is to describe it as:
A device which processes information according to instructions it has been
given.
This general definition rules out fridges but is not exhaustive. However for our
purposes it will do. The instructions you give to the computer are often called a
program. The business of using a computer is often called programming. This
is not what most people do with computers. Most users do not write programs,
instead they talk to programs written by other people. We must therefore make
a distinction between users and programmers. A user has a job which he or she
finds easier to do on a computer running the appropriate program. A
programmer has a masochistic desire to tinker with the innards of the machine.
One of the golden rules is that you never write your own program if there is
already one available, i.e. a keen desire to process words with a computer
should not result in you writing a word processor!
However, because you will often want to do things with computers which have
not been done before, and further because there are people willing to pay you to
do it, we are going to learn how to program as well as use a computer.
Before we can look at the fun packed business of programming though it is
worth looking at some computer terminology:
Hardware and Software
If you ever buy a computer you are not just getting a box which humms. The
box, to be useful, must also have sufficient built in intelligence to understand
simple commands to do things. At this point we must draw a distinction
between the software of a computer system and the hardware.
Hardware is the physical side of the system. Essentially if you can kick it, and it
stops working when immersed in a bucket of water, it is hardware. Hardware is
the impressive pile of lights and switches in the corner....
Software is what makes the machine tick. If a computer has a soul it keeps it in
its software. Software uses the physical ability of the hardware, which can run
programs, do something useful. It is called software because it has no physical
Computers ? 2
existence and it is comparatively easy to change. Software is the voice which
says "Computer Running" in a Star Trek film.
We are going to use an
operating system called MS-
DOS. Later we will be using
UNIX.
All computers are sold with some software. Without it they would just be a novel
and highly expensive heating system. The software which comes with a computer is
often called its Operating System. The Operating System makes the machine
usable. It looks after all the information held on the computer and provides lots of
commands to allow you to manage things. It also lets you run programs, ones you
have written and ones from other people. You will have to learn to talk to an
operating system so that you can create your C programs and get them to go.
Data and Information
People use the words data and information interchangeably. They seem to think
that one means the other. I regard data and information as two different things:
Data is the collection of ons and offs which computers store and manipulate.
Information is the interpretation of the data by people to mean something.
Strictly speaking computers process data, humans work on information. An
example, the computer holds the bit pattern:
11111111 11111111 11111111 00000000
However you could regard this as meaning:
"you are 256 pounds overdrawn at the bank"
or
"you are 256 feet below the surface of the ground"
or
"eight of the thirty two light switches are off"
The transition from data to information is usually made when the human reads
the output. So why am I being so pedantic? Because it is vital to remember that
a computer does not "know" what the data it is processing actually means. As
far as it is concerned data is just patterns of bits, it is you who gives meaning to
these patterns. Remember this when you get a bank statement which says that
you have £8,388,608!
Data Processing
Computers are data processors. Information is fed into them, they do something
with it, and then generate further information. A computer program tells the
computer what to do with the information coming in. A computer works on
data in the same way that a sausage machine works on meat, something is put
in one end, some processing is performed, and something comes out of the
other end:
Data Computer Data
This makes a computer a very
good "mistake amplifier", as
well as a useful thing to
blame.....
A program is unaware of the data it is processing in the same way that a sausage
machine is unaware of what meat is. Put a bicycle into a sausage machine and it
will try to make sausages out of it. Put duff data into a computer and it will do
equally useless things. It is only us people who actually ascribe meaning to data (see
above), as far a the computer is concerned it is just stuff coming in which has to be
manipulated in some way.
Computers ? 3
A computer program is just a sequence of instructions which tell a computer
what to do with the data coming in, and what form the data sent out will have.
Note that the data processing side of computers, which you might think is
entirely reading and writing numbers, is much more than that, examples of
typical data processing applications are:
Digital Watch : A micro-computer in your watch is taking pulses from a
crystal and requests from buttons, processing this data and producing a display
which tells you the time.
Car : A micro-computer in the engine is taking information from sensors
telling it the current engine speed, road speed, oxygen content of the air, setting
of the accelerator etc and producing voltages out which control the setting of
the carburettor, timing of the spark etc, to optimise the performance of the
engine.
CD Player : A computer is taking a signal from the disk and converting it into
the sound that you want to hear. At the same time it is keeping the laser head
precisely positioned and also monitoring all the buttons in case you want to
select another part of the disk.
Note that some of these data processing applications are merely applying
technology to existing devices to improve the way they work. However one, the
CD player, could not be made to work without the built-in data processing
ability.
Most reasonably complex devices contain data processing components to
optimise their performance and some exist only because we can build in
intelligence. It is into this world that we, as software writers are moving. It is
important to think of business of data processing as much more than working
out the company payroll, reading in numbers and printing out results. These are
the traditional uses of computers.
Note that this "raises the
stakes" in that the
consequences of software
failing could be very
damaging.
As engineers it is inevitable that a great deal of our time will be spent fitting data
processing components into other devices to drive them. You will not press a switch
to make something work, you will press a switch to tell a computer to make it work.
These embedded systems will make computer users of everybody, and we will have
to make sure that they are not even aware that there is a computer in there!
Programming Languages ? 4
Programming Languages
What is Programming?
I tell people I am a "Software
Engineer".
Programming is a black art. It is the kind of thing that you grudgingly admit to
doing, at night, with the blinds drawn and nobody watching. Tell people that you
program computers and you will get one of the following responses:
1. A blank stare.
2. "That's interesting", followed by a long description of the double
glazing that they have just had fitted.
3. "My younger brother has a Sinclair Spectrum. He's a programmer
as well."
4. A look which indicates that you can't be a very good one as they
all drive Ferraris and tap into the Bank of England at will.
Programming is defined by most people as earning huge sums of money doing
something which nobody can understand.
Programming is defined by me as deriving and expressing a solution to a given
problem in a form which a computer system can understand and execute.
One or two things fall out of this definition:
? You need to be able to solve the problem yourself before you can
write a program to do it.
? The computer has to be made to understand what you are trying to
tell it to do.
We are back to the term
"Software Engineer" again!
I like to think of a programmer as a bit like a plumber! A plumber will arrive at a
job with a big bag of tools and spare parts. Having looked at it for a while, tut
tutting, he will open his bag and produce various tools and parts, fit them all
together and solve your problem. Programming is just like this. You are given a
problem to solve. You have at your disposal a big bag of tricks, in this case a
programming language. You look at the problem for a while and work out how to
solve it and then fit the bits of the language together to solve the problem you have
got. The art of programming is knowing which bits you need to take out of your bag
of tricks to solve each part of the problem.
Programming Languages ? 5
From Problem to Program
Programming is not about
mathematics, it is about
organisation.
The art of taking a problem and breaking it down into a set of instructions you can
give a computer is the interesting part of programming. Unfortunately it is also the
most difficult part of programming as well. If you think that learning to program is
simply a matter of learning a programming language you are very wrong. In fact if
you think that programming is simply a matter of coming up with a program which
solves a problem you are equally wrong!
There are many things you must consider when writing a program; not all of
them are directly related to the problem in hand. I am going to start on the basis
that you are writing your programs for a customer. He or she has problem and
would like you to write a program to solve it. We shall assume that the
customer knows even less about computers than we do!
Initially we are not even going to talk about the programming language, type of
computer or anything like that, we are simply going to make sure that we know
what the customer wants. Coming up with a perfect solution to a problem the
customer has not got is something which happens surprisingly often in the real
world.
The worst thing you can say
to a customer is "I can do
that". Instead you should
think "Is that what the
customer wants?".
This is almost a kind of self discipline. Programmers pride themselves on their
ability to come up with solutions, so as soon as they are given a problem they
immediately start thinking of ways to solve it, this almost a reflex action. What you
should do is think "Do I really understand what the problem is?". Before you solve a
problem you should make sure that you have a watertight definition of what the
problem is, which both you and the customer agree on. In the real world this is
often called a Functional Design Specification or FDS. This tells you exactly what
the customer wants. Both you and the customer sign it, and the bottom line is that if
you provide a system which behaves according to the design specification the
customer must pay you. Once you have got your design specification, then you can
think about ways of solving the problem.
You might think that this is not necessary if you are writing a program for
yourself; there is no customer to satisfy. This is not true. Writing an FDS forces
you to think about your problem at a very detailed level.
A Simple Problem
Consider the scenario; You are sitting in your favourite chair in the pub
contemplating the universe when you are interrupted in your reverie by a friend
of yours who sells double glazing for a living. He knows you are a programmer
of sorts and would like your help in solving a problem which he has:
He has just started making his own window units and is looking for a program
which will do the costing of the materials for him. He wants to just enter the
dimensions of the window and then get a print out of the cost to make the
window, in terms of the amount of wood and glass required.
"This looks like a nice little earner" you think, and once you have agreed a
price you start work. The first thing you need to do is find out exactly what the
customer wants you to do...
Specifying the Problem
When considering how to write the specification of a system there are three
important things :
? What information flows into the system.
? What flows out of the system.
? What the system does with the information.
Programming Languages ? 6
There are lots of ways of representing this information in the form of diagrams,
for now we will stick with written text when specifying each of the stages:
Information going in
In the case of our immortal double glazing problem we can describe the
information as:
? The width of a window.
? The height of the window.
Information coming out
The information that our customer wants to see is :
? the area of glass required for the window
? the length of wood required to build a frame.
What the program actually does
The program can derive the two values according to the following equations :
glass area = width of window * height of window
wood length = (width of window + height of window) * 2
Putting in more detail
We now have a fairly good understanding of what our program is going to do
for us. Being sensible and far thinking people we do not stop here, we now have
to worry about how our program will decide when the information coming in is
actually valid.
This must be done in conjunction with the customer, he or she must understand
that if information is given which fits within the range specified, your program
will regard the data as valid and act accordingly.
In the case of the above we could therefore expand the definition of data coming
in as :
? The width of the window, in metres and being a value between 0.5
Metres and 3.5 metres inclusive.
? The height of the window, in metres and being a value between
0.5 metres and 2.0 metres inclusive.
Note that we have also added units to our description, this is very important -
perhaps our customer buys wood from a supplier who sells by the foot, in which
case our output description should read :
? The area of glass required for the window, in square metres.
? The length of wood required for the frame, given in feet using the
conversion factor of 3.25 feet per metre.
Note that both you and the
customer must understand
the document!
Having written this all up in a form that both you and the customer can understand,
we must then both sign the completed specification, and work can commence. In a
real world you would now create a procedure which will allow you to prove that the
program works, you could for example say :
If I give the above program the inputs 2 metres high and 1 metre wide the
program should print out : 2 square metres of glass and 9.75 feet of wood.
The test procedure which is designed for a proper project should test out all
possible states within the program, including the all important error conditions.
Programming Languages ? 7
In a large system the person writing the program may have to create a test
harness which is fitted around the program and will allow it to be tested. Both
the customer and the supplier should agree on the number and type of the tests
to be performed and then sign a document describing these.
Better yet, set up a phased
payment system so that you
get some money as the system
is developed.
At this point the supplier knows that if a system is created which will pass all the
tests the customer has no option but to pay him for the work! Note also that because
the design and test procedures have been frozen, there is no ambiguity which can
lead to the customer requesting changes to the work although of course this can still
happen!
Note also in a "proper" system the customer will expect to be consulted as to
how the program will interact with the user, sometimes even down to the colour
of the letters on the display! Remember that one of the most dangerous things
that a programmer can think is "This is what he wants"! The precise interaction
with the user - what the program does when an error is encountered, how the
information is presented etc., is something which the customer is guaranteed to
have strong opinions about. Ideally all this information should be put into the
specification, which should include layouts of the screens and details of which
keys should be pressed at each stage.
Fact: If you expect to derive
the specification as the
project goes on either you
will fail to do the job, or you
will end up performing five
times the work!
If this seems that you are getting the customer to help you write the program then
you are exactly right! Your customer may have expected you to take the description
of the problem and go into your back room - to emerge later with the perfect
solution to the problem. This is not going to happen. What will happen is that you
will come up with something which is about 60% right. The customer will tell you
which bits look OK and which bits need to be changed. You then go back into your
back room, muttering under your breath, and emerge with another system to be
approved. Again, Robert's law says that 60% of the duff 40% will now be OK, so
you accept changes for the last little bit and again retreat to your keyboard....
The customer thinks that this is great, reminiscent of a Saville Row tailor who
produces the perfect fit after numerous alterations. All the customer does is look
at something, suggests changes and then wait for the next version to find
something wrong with.....
Fact: More implementations
fail because of inadequate
specification than for any
other reason!
If your insisting on a cast iron specification forces the customer to think about
exactly what the system is supposed to do and how it will work, all to the better.
The customer may well say "But I am paying you to be the computer expert, I know
nothing about these machines". This is no excuse. Explain the benefits of "Right
First Time" technology and if that doesn't work produce a revolver and force the
issue!
Again, if I could underline in red I would : All the above apply if you are
writing the program for yourself. You are your own worst customer!
You may think that I am labouring a point here, the kind of simple systems we
are going to create as we learn to program are going to be so trivial that the
above techniques are far too long winded. You are wrong. One very good
reason for doing this kind of thing is that it gets most of the program written for
you - often with the help of the customer. When we start with our double
glazing program we now know that we have to :
read in the width
verify the value
read in the height
verify the value
calculate width times height and print it
calculate ( width + height ) * 2 * 3.35 and print it
The programming portion of the job is now simply converting the above
description into a language which can be used in a computer.......
C ? 8
Programming Languages
You might ask the question "Why do we need programming languages, why
can we not use something like English?" There are two answers to this one:
1. Computers are too stupid to understand English.
2. English would make a lousy programming language.
Please note that this does not
imply that tape worms would
make good programmers!
To take the first point. We cannot make very clever computers at the moment.
Computers are made clever by putting software into them, and there are limits to
the size of program that we can create and the speed at which it can talk to us. At
the moment, by using the most advanced software and hardware, we can make
computers which are about as clever as a tape worm. Tape worms do not speak very
good English, therefore we cannot make a computer which can understand English.
The best we can do is get a computer to make sense of a very limited language
which we use to tell it what to do.
Time Files like an Arrow.
Fruit Flies like a Banana!
To take the second point. English as a language is packed full of ambiguities. It is
very hard to express something in an unambiguous way using English, if you do not
believe me, ask any lawyer!
Programming languages get around both of these problems. They are simple
enough to be made sense of by computer programs and they reduce ambiguity.
There are very many different programming languages around, you will need to
know more than one if you are to be a good programmer.
C
A look at C
There are literally hundreds
of programming languages
around, you will need to
know at least 3!
We are going to learn a language called C. C is a very flexible and powerful
programming language originally designed in the early 1970s. It is famous as the
language the UNIX operating system was written in, and was specially designed for
this. However its use has now spread way beyond that field and it is currently very
popular.
C is a professional language. So what do I mean by that? Consider the chain
saw. If I, Rob Miles, want to use a chain saw I will hire one from a shop. As I
am not an experienced chain saw user I would expect it to come with lots of
built in safety features such as guards and automatic cut outs. These will make
me much safer with the thing but will probably limit the usefulness of the tool,
i.e. because of all the safety stuff I might not be able to cut down certain kinds
of tree. If I was a real lumberjack I would go out and buy a professional chain
saw which has no safety features whatsoever but can be used to cut down most
anything. If I make a mistake with the professional tool I could quite easily lose
my leg, something the amateur machine would not let happen.
C ? 9
In programming terms this means is that C lacks some safety features provided
by other programming languages. This makes the language much more flexible.
However, if I do something stupid C will not stop me, so I have a much greater
chance of crashing the computer with a C program than I do with a safer
language.
This is not something to worry about, you should always work on the basis that
any computer will tolerate no errors on my part and anything that I do which is
stupid will always cause a disaster!
Making C Run
You actually write the
program using some form of
text editor - which may be
part of the compiling and
linking system.
C is usually a compiled programming language. The computer cannot understand
the language directly, so a program called a compiler converts the C into the
machine code instructions which do the job. Actually getting a program to run is
however a two stage process. First you show your program, often called the source,
to the compiler. If the compiler gives it the thumbs up you then perform a process
called linking.
Linking is when all the various portions of your program are brought together
to form something which can be run. You might ask "Why to we link things? -
the compiler has created a machine code version of my program, can't I just run
that?". The reason that we have the additional linking process is that it allows
us to reuse standard pieces of code from a library. Many things your program
will do are common to lots of other programs, for example you will want to
read information from the keyboard and you will want to send information to
the display. Rather than compile the program code which does this every time
you compile your program, a much more efficient way is to put a compiled
version of this code into a library. Your program just contains a reference to the
particular function you want to use, the linker then loads the relevant part from
the library when it creates your program.
It is possible to get the
compiler to give you
warnings in this case.
Note that a side effect of this is that if you refer to a function which does not exist,
the compiler will not mind particularly - but the linker will not find the item in its
library, and thus give you an error.
Once the linker has finished you are left with a free standing file which is your
program. If you run this your program gets control!
Creating C Programs
The actual business of constructing and compiling the depends on the computer
you are using and the particular version of C. We will look at the business of
producing your program in the laboratory section of this course. Initially it is
best if we just work through your programs on paper. I reckon that you write
programs best when you are not sitting at the computer, i.e. the best approach is
to write (or at least map out) your solution on paper a long way away from the
machine. Once you are sitting in front of the keyboard there is a great
temptation to start pressing keys and typing something in which might work.
This is not good technique. You will almost certainly end up with something
which almost works, which you will then spend hours fiddling with to get it
going.
If you had sat down with a pencil and worked out the solution first you would
probably get to a working system in around half the time. I am not impressed by
hacking programmers who spend whole days at terminals fighting with
enormous programs and debugging them into shape. I am impressed by
someone who turns up, types in the program and makes it work first time!
C ? 10
What Comprises a C Program?
A program is the thing that you write to perform a particular task.
It will actually be a file of text, often called a source file. This is what the
compiler acts on. A source file contains three things :
? instructions to the compiler
? information about the structures which will hold the data to be
stored and manipulated.
? instructions which manipulate the data.
To take these in turn
Controlling the Compiler
The compiler directives are
the same for all versions of
C.
One of the very powerful features of C is the way in which you can change the way
the compiler processes your program by including directives. There are many
directives available, in a C program a directive is always preceded by the #
character and must appear right at the beginning of a line. Directives can be used
to "build in" particular values, for example constants like PI, and also allow you to
change which parts of the program which the compiler works on, making it
possible to use the same piece of program on several different types of computer.
Storing the Data
Programs work by processing data. The data has to be stored within the
computer whilst the program processes it. All computer languages support
variables of one form or another. A variable is simply a named location in
which a value is held whilst the program runs. C also lets you build up
structures which can hold more than one item, for example a single structure
could hold all the information about a particular bank customer.
Describing the Solution
The actual instructions which describe your solution to the problem must also
be part of your program. In the case of C a lump of program which does one
particular thing is called a function.
Seasoned programmers break
down a problem into a
number of smaller ones and
make a function for each.
A function can be very small, or very large. It can return a value which may or may
not be of interest. It can have any name you like, and your program can contain as
many functions as you see fit. One function may refer to others. The C language
also has a large number of function libraries available which you can use. These
save you from "re-inventing the wheel" each time you write a program.
Within the function there will be a number of statements. A statement is an
instruction to perform one particular operation, for example add two numbers
together and store the result. The really gripping thing about programs is that a
statement can decide which statement is performed next, so that your program
can look at things and decide what to do.
You give a name to each function that you create, and you try to make the name
of the function fit what it does, for example menu or save_file. The C
language actually runs your program by looking for a function with a special
name, main. This function is called when your program starts running, and
when main finishes, your program ends.
A First C Program ? 11
The Advantages of C
The good news about C is that you can write code which runs quickly, and your
program is very "close to the hardware". By that I mean that you can access low
level facilities in your computer quite easily, without the compiler or run time
system stopping you from doing something potentially dangerous.
The use of compiler directives to the pre-processor make it possible to produce
a single version of a program which can be compiled on several different types
of computer. In this sense C is said to be very portable. The function libraries
are standard for all versions of C so they can be used on all systems.
The Disadvantages of C
The disadvantages of C fall neatly from the advantages. The biggest one is that
you can write C programs which can fail in very catastrophic ways. These
programs will appear totally valid as far as the compiler is concerned but will
not work and may even cause your computer to stop. A more picky language
would probably notice that you were doing something stupid in your program
and allow you to find the error before it crashed your computer! However a
more picky language would probably not allow you to write the program in the
first place!
Another disadvantage of C is that it allows you to write very terse code. You
can express exactly what you want to do in very few statements. You might
think that this is nice, because it makes your programs even more efficient, but
it has the side effect of making them much harder to understand. At the time
you write the code you know exactly what each part is supposed to do. If you
come back to the program in several months you will need time to "get back
inside it". If the code is written very tightly you will take much longer to do
this, and other people may not be able to understand it at all! I write code which
is not the most efficient possible, but is easy to understand. I am sacrificing
program performance for ease of maintenance.
A First C Program
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:
A First C Program ? 12
#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?
#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. (see later)
<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
Some C programs have the
type of int so that the main
function can return a value to
the operating system which
runs it. We are not going to
do this.
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.
A First C Program ? 13
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
A First C Program ? 14
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.
A First C Program ? 15
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.
A First C Program ? 16
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 :
Format Command
%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.
A First C Program ? 17
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
#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 metr es.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....
Variables ? 18
Variables
Variables and Data
Programs operate on data. A programming language must give you a way of
storing the data you are processing, otherwise it is useless. What the data
actually means is something that you as programmer decide (see above
digression on data).
Types of Variables
Basically there are two types of data:
? Nice chunky individual values, for example the number of sheep
in a field, teeth on a cog, apples in a basket.
? Nasty real world type things, for example the current temperature,
the length of a piece of string, the speed of a car.
In the first case we can hold the value exactly; you always have an exact
number of these items, they are integral.
When you are writing a
specification you should
worry about the precision to
which values are to be held.
Too much accuracy may slow
the machine down - too little
may result in the wrong
values being used.
In the second case we can never hold what we are looking at exactly. Even if you
measure a piece of string to 100 decimal places it is still not going to give you its
exact length - you could always get the value more accurately. These are real. A
computer is digital, i.e. it operates entirely on patterns of bits which can be regarded
as numbers. Because we know that it works in terms of ons and offs it has problems
holding real values. To handle real values the computer actually stores them to a
limited accuracy, which we hope is adequate (and usually is).
This means that when we want to store something we have to tell the computer
whether it is an integer or a real. In fact it is useful to have several types of
data.
Declaration
Robs' Arbitrary Standard For
Coloured Boxes!
You tell C about something you want to store by declaring it. The declaration also
identifies the type of the thing we want to store. Think of this as C creating a box of
a particular size, specifically designed to hold items of the given type. We identify
what type of data a particular box can hold by making it a certain colour, according
to RASFCB integer boxes are coloured red and real (or floating point) boxes are
coloured green.
Variables ? 19
Note that C is often called weakly typed. This does not mean that you do not
press the keys very hard (ho ho), what it means is that C does not fuss about
what you put in each box. If you have a red box (of type integer), and then ask
C to put a green value into it (of type real or floating point), C will not
complain that what you want to do is meaningless, it will just do it. Other
languages, for example PASCAL, get all hot under the collar when you try to
do this, they are called strongly typed. Weakly typed languages let you do
exactly what you want so, provided you know what you are doing, everything
will work out OK.
We will consider just three types for the moment, there are others available but
you can get by with these for now:
int variables
Note that we can go one
further negative than
positive. This is because the
numbers are stored using "2's
complement" noation.
A type of box which can hold only integer values, i.e. no fractional part. The precise
range of integers which are supported varies from one version of C to another, in
the version we are using it goes from -32768 to +32767
float variables
A type of box which can hold a real (i.e. floating point) number. These are held
to limited precision, again the precision and range you get varies from one
version of C to another, in the version of C we are using it goes from 3.4E-38
to 3.4E+38.
char variables
A type of box which can hold a single character. We have already come across
characters when we looked at filenames and the like. A character is what you
get when you press a key on a keyboard.
Missing Types
If you are used to other languages you might think that there are some storage
types missing, for example there is no way to store strings of characters. In C,
unlike BASIC, you have to manage the storage of strings yourself - however
there are a large number of built in facilities to make like easier. We will come
to these later.
Another missing type is that used to store logical values, i.e. either TRUE or
FALSE. C does not provide this facility, but uses the convention throughout
that 0 means false and any other value means true. There are operators that can
be used to provide logical combinations in C, but they will work on any non-
real data type.
Variable Declaration
Before you can use a particular box you have to tell the compiler about it. C will
not just create boxes for you; it has to know the name of the box and what you
are going to put into it. You tell C about a box by declaring it.
When the compiler is given a declaration it says something along the lines of:
Variables ? 20
Here is the name of something which we want to store. I will create a box of the
type requested, paint it the correct colour and write the name on it. Later on I
will put things in the box and get things out of it. I will put the box on a shelf
out of the way for now.
Such a box is often called a variable. All languages support different types of
variables, all have types equivalent to the C ones.
Remember that all we have is a box. The box is not empty at the moment, but
there is nothing of interest in it; the contents are what we call undefined. If you
use the contents of an undefined variable you can look forward to your program
doing something different each time you run it!
C paints the name on the box using a stencil. There are only a few stencils
available, so the characters that you can use to name a variable are limited.
Also, because of the design of the stencils themselves, there are some rules
about how the names may be formed, namely:
? All variable names must start with a letter.
? After the letter you can have either letters or numbers or the
underscore "_" character.
The length of the name allowed depends on the version of C you are using. You
can use amazingly long names in any version of C, the important thing to
remember is that only a certain number of characters are looked at, i.e.
very_long_and_impressive_C_variable_called_fred
and
very_long_amd_impressive_C_variable_called_jim
- would probably be regarded as the same in most versions of C.
Upper and lower case letters are different, i.e. Fred and fred are different
variables.
Here are a few example declarations, one of which are not valid (see if you can
guess which one and why) :
int fred ;
float jim ;
char 29yesitsme ;
One of the golden rules of programming, along with "always use the keyboard
with the keys uppermost" is:
Always give your variables meaningful names.
According to the Mills and Boon romances that I have read, the best
relationships are meaningful ones.
Giving Values to Variables
Once we have got ourselves a variable we now need to know how to put
something into it, and get the value out. C does this by means of an assignment.
There are two parts to an assignment, the thing you want to assign and the
place you want to put it, for example consider the following:
Variables ? 21
void main ( void )
{
int first, second, third ;
first = 1 ;
second = 2 ;
second = second + first ;
}
The first part of the program should be pretty familiar by now. Within the
main function we have declared three variables, first, second and third.
These are each of integer type.
The last three statements are the ones which actually do the work. These are
assignment statements. An assignment gives a value to a specified variable,
which must be of a sensible type (note that you must be sensible about this
because the compiler, as we already know, does not know or care what you are
doing). The value which is assigned is an expression. The equals in the middle
is there mainly do confuse us, it does not mean equals in the numeric sense, I
like to think of it as a gozzinta (see above). Gozzintas take the result on the
right hand side of the assignment and drop it into the box on the left, which
means that:
2 = second + 1 ;
is a piece of programming naughtiness which would cause all manner of nasty
errors to appear.
Expressions
An expression is something which returns a result. We can then use the result
as we like in our program. Expressions can be as simple as a single value and
as complex as a large calculation. They are made up of two things, operators
and operands.
Operands
Operands are things the operators work on; They are usually constant values or
the names of variables. In the program above first, second, third and 2 are
all operands.
Operators
Operators are the things which do the work; They specify the operation to be
performed on the operands. Most operators work on two operands, one each
side. In the program above + is the only operator.
Here are a few example expressions:
2 + 3 * 4
-1 + 3
(2 + 3) * 4
These expressions are worked out (evaluated) by C moving from left to right,
just as you would yourself. Again, just as in traditional maths all the
multiplication and division is performed first in an expression, followed by the
addition and subtraction.
C does this by giving each operator a priority. When C works out an expression
it looks along it for all the operators with the highest priority and does them
first. It then looks for the next ones down and so on until the final result is
obtained. Note that this means that the first expression above will therefore
return 14 and not 20.
Variables ? 22
If you want to force the order in which things are worked out you can put
brackets around the things you want done first, as in the final example. You can
put brackets inside brackets if you want, provided you make sure that you have
as many open ones as close ones. Being a simple soul I tend to make things
very clear by putting brackets around everything.
It is probably not worth getting too worked up about this expression evaluation
as posh people call it, generally speaking things tend to be worked out how you
would expect them.
For completeness here is a list of all operators, what they do and their
precedence (priority). I am listing the operators with the highest priority first.
op. use
- unary minus, the minus that C finds in negative numbers, e.g. -1.
Unary means applying to only one item.
* multiplication, note the use of the * rather than the more
mathematically correct but confusing x.
/ division, because of the difficulty of drawing one number above
another on a screen we use this character instead
+ addition, no problems here.
- subtraction. Note that we use exactly the same character as for unary
minus.
This is not a complete list of all the operators available, but it will do for now.
Because these operators work on numbers they are often called the numeric
operators.
Types of Data in Expressions
When C performs an operator, it makes a guess as to the type of the result that
is to be produced. Essentially, if the two operands are integer, it says that the
result should be integer, if the two are floating point, it says that the result
should be floating point. This can lead to problems, consider the following :
1/2
1/2.0
You might think that these would give the same result. Not so. The compiler
thinks that the first expression, which involves only integers, should give an
integer result. It therefore would calculate this to be the integer value 0 (the
fractional part is always truncated). The second expression, because it involves
a floating point value would however be evaluated to give a floating point
result, the correct answer of 0.5
Casting
We can force C to regard a value as being of a certain type by the use of casting.
A cast takes the form of an additional instruction to the compiler to force it
regard a value in a particular way. You cast a value by putting the type you
want to see there in brackets before it. For example :
Variables ? 23
#include <stdio.h>
void main ( void )
{
int i = 3, j = 2 ; float fraction ;
fraction = (float) i / (float) j ;
printf ( "fraction : %f n", fraction ) ;
}
The (float) part of the above tells the compiler to regard the values in the
integer variables as floating point ones, so that we get 1.5 printed out rather
than 1.
When you cast, which you need to do occasionally, remember that casting does
not affect the actual value, just how C regards the number. As we saw above,
each type of variable has a particular range of possible values, and the range of
floating point values is much greater than that for integers. This means that if
you do things like :
int i ;
i = (int) 12345678.999 ;
I do not think of this as a
failing in C. It gives you
great flexibility, at the cost of
assuming you know what you
are doing....
- the cast is doomed to fail. The value which gets placed in i will be invalid.
Nowhere in C does the language check for mistakes like this. It is up to you when
you write your program to make sure that you never exceed the range of the data
types you are using - the program will not notice but the user certainly will!
Getting Values into the Program
We have used the printf (print-formatted) standard input/output procedure
from stdio.h to do the output, what we need is an equivalent procedure to do the
input. C has got one of these, it is called scanf (scan-formatted). However,
before we can turn it loose we have a little problem to solve; Where does scanf
put the value that it fetches. "That is easy" you say, simply give it the name of
the variable and scanf will know where to go. Wrong! scanf is very stupid. It
cannot understand the names of variables. Why should it? All it was created for
is to take something from one place (the keyboard) and put it somewhere else (a
location). scanf does not want to know what the variable is called, all it needs
to know is where the variable lives.
When we talk about C variables we mean a box which the compiler creates for
us, with a name nicely painted on it. The compiler makes a box like this and
then puts it on a shelf somewhere safe. The compiler then knows that when we
say "i" we really mean the box with i written on it. scanf is simply a function
that we call to fetch a value and stick it somewhere else, another kind of
removal man. It needs to be told which box to put the result in. C calls referring
to a thing by its location rather than its name as pointing.
Nice children have been brought up knowing that it is rude to point. In C things
are rather different, you have to point to be able to do anything useful. (I am
sure nanny would understand).
For more about pointers, see
the chapter about Functions.
When we want scanf to fetch something for us we have to give it a pointer. You
can regard a pointer as a tag on the end of a piece of rope. The rope is tied to one of
our boxes. All scanf has to do is follow the piece of rope to a box and then put the
value into that box.
You tell the C compiler to generate a pointer to a particular variable by putting
an ampersand "&" in front of the variable name, i.e.
x means the value of the variable x
Writing a Program ? 24
&x means a pointer to the box where x is kept, i.e. the address of x.
scanf looks very like printf, in that it is a format string followed by a list of
items, but in this case the items pointers to variables, rather than values, for
example:
scanf ( "%d %d %d", &i, &j, &k) ;
The more adventurous amongst you may be wondering what happens if we
leave off the ampersands by mistake. This can lead to one of two things:
1. The compiler noticing that you have been a naughty programmer
and taking you behind the bike sheds for a meaningful discussion.
2. scanf taking the value which it gets and stuffing it into a spurious
chunk of memory, with the consequent and hilarious total failure
of program and possibly computer.
A very big chunk of C involves address and pointer juggling. I make no
apologies for this, it is one of the things that makes C the wonderful, fun
loving, language that it is. However it can also be a little hard on the grey
matter. Just keep in mind that only the C compiler can handle sticking values
into variables. Everything else does not know the name, and can only talk in
terms of following pointers to boxes.
Writing a Program
Comments
When the C compiler sees the "/*" sequence which means the start of a
comment it says:
Aha! Here is a piece of information for greater minds than mine to ponder. I
will ignore everything following until I see a */ which closes the comment.
Be generous with your comments. They help to make your program much easier
to understand. You will be very surprised to find that you quickly forget how
you got your program to work. You can also use comments to keep people
informed of the particular version of the program, when it was last modified
and why, and the name of the programmer who wrote it - if you dare!
Program Flow
The program above is very simple, it runs straight through from the first
statement to the last, and then stops. Often you will come across situations
where your program must change what it does according to the data which is
given to it. Basically there are three types of program flow :
Writing a Program ? 25
1. straight line
2. chosen depending on a given condition
3. repeated according to a given condition
Every program ever written is composed of the three elements above, and very
little else! You can use this to good effect when designing an overall view of
how your program is going to work. At the moment we have only considered
programs which run in a straight line and then stop. The path which a program
follows is sometimes called its "thread of execution". When you call a function
the thread of execution is transferred into the function until it is complete.
Conditional Execution - if
The program above is nice, in fact our customer will probably be quite pleased
with it. However, it is not perfect. The problem is not with the program, but
with the user.
If you give the program a window width of -1 it goes ahead and works out a
stupid result. Our program does not have any checking for invalid widths and
heights. The user might have grounds for complaint if the program fails to
recognise that he has given a stupid value, in fact a number of cases are
currently being fought in the United States courts where a program has failed to
recognise invalid data, produced garbage and caused a lot of damage.
What we want to do is notice the really stupid replies and tell the user that he
has done something dubious. In our program specification, which we give the
customer, we have said something like:
The program will reject window dimensions outside the following ranges:
width less than 0.5 metres
width greater than 5.0 metres
height less than 0.75 metres
height greater than 3.0 metres
This means that we have done all we can; If the program gets 1 rather than 10
for the width then that is the users' problem, the important thing from our point
of view is that the above specification stops us from being sued!
In order to allow us to do this the program must notice naughty values and
reject them. To do this we need can use the construction:
if (condition)
statement or block we do if the condition is true
else
statement or block we do if the condition is false
The condition determines what happens in the program. So what do we mean
by a condition? C is very simple minded about this, essentially it says that any
condition which is non-zero is true, any condition which is zero is false. A
condition is therefore really something which returns a number, for example:
if (1)
printf ( "hello mum" ) ;
- is valid, although rather useless as the condition is always true, so "hello
mum" is always printed (note that we left the else portion off - this is OK
because it is optional).
Writing a Program ? 26
Conditions and Relational Operators
To make conditions work for us we need a set of additional relational operators
which we can use to make choices. Relational operators work on operands, just
like numeric ones. However any expression involving them can only produce
two values, 0 or 1. Zero if the expression is not true, one if it is. Relational
operators available are as follows:
==
equals. If the left hand side and the right hand side are equal the expression has
the value 1. If they are not equal the value is 0.
4 == 5
- would return 0, i.e. false. Note that it is not meaningful to compare floating
point values in this way. Because of the fact that they are held to limited
precision you might find that conditions fail when they should not for example
the following equation :
x = 3.0 * ( 1.0 / 3.0) ;
- may well result in x containing 0.99999999, which would mean that :
(x == 1.0)
If you want to compare
floating point values subtract
them and see if the difference
is very small.
- would be false - even though mathematically the test should return true.
!=
not equal. The reverse of equal. If they are not equal the expression has the
value 1, if they are equal it has the value 0. Again, this test is not suitable for
use with floating point numbers.
<
less than. If the item on the left is less than the one on the right the value of the
expression is 1. If the left hand value is larger than or equal to the right hand
one the expression gives 0. It is quite valid to compare floating point numbers
in this way.
>
greater than. If the expression on the left is greater than the one on the right the
result is 1. If the expression on the left is less than or equal to the one on the
right the result is 0.
<=
less than or equal to. If the expression on the left is less than or equal to the one
on the right you get 1, otherwise you get 0.
>=
greater than or equal to. If the value on the left is greater than or equal to the
one on the right you get 1, otherwise it is 0.
Writing a Program ? 27
!
not. This can be used to invert a particular value or expression, for example you
can say !1, which is 0, or you could say: !(x=y) - which means the same as
(x!=y). You use not when you want to invert the sense of an expression.
Combining Logical Operators
Sometimes we want to combine logical expressions, to make more complicated
choices, for example to test for a window width being valid we have to test that
it is greater than the minimum and less than the maximum. C provides
additional operators to combine logical values :
&&
and. If the expressions each side of the && are true the result of the && is true.
If one of them is false the result is false, for example
(width > 0.5) && (width < 5.0) )
- this would be true if the width was valid according to our above description.
||
or. If either of the expressions each side of the || are true the result of the whole
expression is true. The expression is only false if both expressions are false, for
example :
(width <= 0.5) | (width >= 5.0) )
De Morgans theorem is the
basis of this.
- this would be true if the width was invalid according to our above description.
Note that if we put an or in we have to also flip the conditional operators around as
well.
Using these operators in conjunction with the if statement we can make
decisions and change what our program will do in response to the data we get.
Lumping Code Together
We have decided that if the user gives a value outside our allowed range an
error is generated and the value is then set to the appropriate maximum or
minimum. To do this we have to do two statements which are selected on a
particular condition, one to print out the message and the other to perform an
assignment. You can do this by using the { and } characters. A number of
statements lumped together between { and } characters is regarded as a single
statement, so we do the following:
if ( width > 5.0 ) {
printf ( "Width too big, using maximum n" ) ;
width = 5.0 ;
}
The two statements are now a block, which is performed only if width is greater
than 5.0. You can lump many hundreds of statements together in this way, the
compiler does not mind. You can also put such blocks of code inside other
blocks, this is called nesting.
The number of { and } characters must agree in your program, otherwise you
will get strange and incomprehensible errors when the compiler hits the end of
the file in the middle of a block or reaches the end of your program half way
down your file!
Writing a Program ? 28
I make things much easier to understand by indenting a particular block by a
number of spaces, i.e. each time I open a block with the { character I move my
left margin in a little way. I can then see at a glance whereabouts I am in the
levels at any time.
Magic Numbers and #define
A magic number is a value with a special meaning. It will never be changed
within the program, it is instead a constant which is used within it. When I
write my glazing program I will include some magic numbers which give the
maximum and minimum values for heights and widths. I could just use the
values 0.5, 5.0, 0.75 and 3.0 - but these are not packed with meaning and
make the program hard to change. If, for some reason, my maximum glass size
becomes 4.5 metres I have to look all through the program and change only the
appropriate values. I do not like the idea of "magic numbers" in programs, what
I would like to do is replace each number with something a bit more
meaningful.
We can do this by using a part of the compiler called the C pre-processor. The
pre-processor sits between your program and the compiler. It can act as a kind
of filter, responding to directives in your program, and doing things to the text
before the compiler sees it. We are just going to look at the one directive at the
moment, #define:
#define PI 3.141592654
Whenever the pre-processor sees PI it sends the compiler 3.141592654. This
means that you can do things like:
circ = rad * 2 * PI ;
The item which follows the #define directive should be a sequence of
characters. You then have a space, followed by another sequence of characters.
Neither of the two sequences are allowed to contains spaces, this would get the
pre-processor confused. Anywhere you use a magic number you should use a
definition of this form, for example:
#define MAX_WIDTH 5.0
This makes your programs much easier to read, and also much easier to change.
There is a C convention that you always give the symbol you are defining in
CAPITAL LETTERS. This is so that when you read your program you can tell
which things have been defined.
Note that the #define directive is not intelligent, and you can therefore stop
your program from working by getting your definition wrong. Consider the
effect of:
#define MAX_WIDTH *this*will*cause*an*explosion!
There are loads more pre-processor directives which you can use, the other one
which we have already seen is #include.
We can therefore modify our double glazing program as follows:
/* Double Glazing 2 */
/* This program calculates glass area and wood */
/* required by a double glazing salesman. */
/* Version 22.15 revision level 1.23 */
/* Rob Miles - University of Hull - 13/11/89 */
#include <stdio.h>
Writing a Program ? 29
#define MAX_WIDTH 5.0
#define MIN_WIDTH 0.5
#define MAX_HEIGHT 3.0
#define MIN_HEIGHT 0.75
void main ()
{
float width, height, glassarea, woodlength ;
printf ( "Give the width of the window : " ) ;
scanf ( "%f", &width ) ;
if (width < MIN_WIDTH) {
printf ( "Width is too small. nn" ) ;
width = MIN_WIDTH ;
}
if (width > MAX_WIDTH) {
printf ( "Width is too large. nn" ) ;
width = MAX_WIDTH ;
}
scanf ( "%f", &height ) ;
if (height < MIN_HEIGHT) {
printf ( "Height is too small. nn" ) ;
height = MIN_HEIGHT ;
}
if (height > MAX_HEIGHT) {
printf ( "Height is too large. nn" ) ;
height = MAX_HEIGHT ;
}
woodlength = 2 * (width + height) ;
glassarea = width * height ;
printf ( "Glass : %f Wood : %f nn", woodlength, glassarea ) ;
}
This program fulfills our requirements. It will not use values incompatible with
our specification. However I would still not call it perfect. If our salesman gives
a bad height the program stops and needs to be re-run, with the height having
to be entered again.
What we would really like is a way that we can repeatedly fetch values for the
width and height until we get one which fits.
C allows us to do this by providing a looping constructions.
Loops
Conditional statements allow you to do something if a given condition is true.
However often you want to repeat something while a particular condition is
true, or a given number of times.
C has three ways of doing this, depending on precisely what you are trying to
do. Note that we get three methods not because we need three but because they
make life easier when you write the program (a bit like an attachment to our
chainsaw to allow it to perform a particular task more easily). Most of the skill
of programming involves picking the right tool or attachment to do the job in
hand. (the rest is finding out why the tool didn't do what you expected it to!).
In the case of our program we want to repeatedly get numbers in until while we
are getting duff ones, i.e. giving a proper number should cause our loop to stop.
Writing a Program ? 30
This means that if we get the number correctly first time the loop will execute
just once. You might think that I have pulled a fast one here, all I have done is
change:
Get values until you see one which is OK
into
Get values while they are not OK
Part of the art of programming is changing the way that you think about the
problem to suit the way that the programming language can be told to solve it.
Further details can be found in Zen and the Art of 68000 Assembler from
Psychic Press at £150.
do -- while loop
In the case of our little C program we use the do -- while construction which
looks like this:
do
statement or block
while (condition) ;
This allows us to repeat a chunk of code until the condition at the end is true.
Note that the test is performed after the statement or block, i.e. even if the test
is bound to fail the statement is performed once.
A condition in this context is exactly the same as the condition in an if
statement, raising the intriguing possibility of programs like:
#include <stdio.h>
void main ()
{
do
printf ( "hello mum n" ) ;
while (1) ;
}
This is a perfectly legal C program. How long it will run for is an interesting
question, the answer contains elements of human psychology, energy futures
and cosmology, i.e. it will run until:
1. You get bored with it.
2. Your electricity runs out.
3. The universe implodes.
This is a chainsaw situation, not a powerful chainsaw situation. Just as it is
possible with any old chainsaw to cut off your leg if you try really hard so it is
possible to use any programming language to write a program which will never
stop. It reminds me of my favourite shampoo instructions:
1. Wet Your Hair
2. Add Shampoo and Rub vigorously.
3. Rinse with warm water.
4. Repeat.
I wonder how many people there are out there still washing their hair at the
moment.
Writing a Program ? 31
while loop
Sometimes you want to decide whether or not to repeat the loop before you
perform it. If you think about how the loop above works the test is done after
the code to be repeated has been performed once. For our program this is
exactly what we want, we need to ask for a value before we can decide whether
or not it is valid. In order to be as flexible as possible C gives us another form
of the loop construction which allows us to do the test first:
while (condition)
statement or block
Note that C makes an attempt to reduce the number of keys you need to press to
run the program by leaving out the word do. (if you put the do in the compiler
will take great delight in giving you an error message - but you had already
guessed that of course!).
for loop
Often you will want to repeat something a given number of times. The loop
constructions we have given can be used to do this quite easily:
#include <stdio.h>
void main ()
{
int i ;
i = 1 ;
while ( i < 11) {
printf ( "hellon" ) ;
i = i + 1 ;
}
}
The variable which controls
things is often called the
control variable, and is
usually given the name i.
This useless program prints out hello 10 times. It does this by using a variable to
control the loop. The variable is given an initial value (1) and then tested each time
we go around the loop. The control variable is then increased for each pass through
the statements. Eventually it will reach 11, at which point the loop terminates and
our program stops.
C provides a construction to allow you to set up a loop of this form all in one:
for ( setup ; finish test ; update ) {
things we want to do a given
number of times
}
We could use this to re-write the above program as:
#include <stdio.h>
void main ()
{
int i ;
for ( i=0 ; i != 11 ; i = i+1 ) {
printf ( "hellon" ) ;
}
}
The setup puts a value into the control variable which it will start with. The test
is a condition which must be true for the for -- loop to continue. The update is
the statement which is performed to update the control variable at the end of
each loop. Note that the three elements are separated by semicolons. The
precise sequence of events is as follows:
Writing a Program ? 32
1. Put the setup value into the control variable.
2. Test to see if we have finished the loop yet and exit to the
statement after the for loop if we have.
3. Perform the statements to be repeated.
4. Perform the update.
5. Repeat from step 2.
Writing a loop in this way is quicker and simpler than using a form of while
because it keeps all the elements of the loop in one place, instead of leaving
them spread about the program. This means that you are less likely forget to do
something like give the control variable an initial value, or update it.
If you are so stupid as to mess around with the value of the control variable in
the loop you can expect your program to do stupid things, i.e. if you put i back
to 0 within the loop it will run forever.....
Breaking Out of Loops
Sometimes you may want to escape from a loop whilst you are in the middle of
it, i.e. your program may decide that there is no need or point to go on and
wishes to tunnel out of the loop and continue the program from the statement
after it.
You can do this with the break statement. This is a command to leap out of the
loop immediately. Your program would usually make some form of decision to
quit in this way. I find it most useful so that I can provide a get the hell out of
here option in the middle of something, for example in the following program
snippet the variable aborted, normally 0 becomes 1 when the loop has to be
abandoned and the variable runningOK, normally 1, becomes 0 when it is
time to finish normally.
while (runningOK) {
complex stuff
....
if (aborted) {
break ;
}
....
more complex stuff
....
}
....
bit we get to if aborted becomes true
....
Note that we are using two variables as switches, they do not hold values as
such, they are actually used to represent states within the program as it runs.
This is a standard programming trick that you will find very useful.
You can break out of any of the three kinds of loop. In every case the program
continues running at the statement after the last statement of the loop.
Going Back to the Top of a Loop
Every now and then you will want to go back to the top of a loop and do it all
again. This happens when you have gone as far down the statements as you
need to. C provides the continue statement which says something along the
lines of:
Writing a Program ? 33
Please do not go any further down this time round the loop. Go back to the top
of the loop, do all the updating and stuff and go around if you are supposed to.
In the following program the variable Done_All_We_Need_This_Time is
set when we have gone as far down the loop as we need to.
for ( item = 1 ; item < Total_Items ; item=item+1 ) {
.....
item processing stuff
....
if (Done_All_We_Need_This_Time) {
continue ;
....
additional item processing stuff
....
}
The continue causes the program to re-run the loop with the next value of
item if it is OK to do so. You can regard it as a move to step 2 in the list above.
More Complicated Decisions
We can now think about using a loop to test for a valid width or height.
Essentially we want to keep asking the user for a value until we get one which
is OK; i.e. if you get a value which is larger than the maximum or smaller than
the minimum ask for another.
To do this we have to combine two tests to see if the value is OK. Our loop
should continue to run if:
width > MAX_WIDTH
or
width < MIN_WIDTH
To perform this test we use one of the logical operators described above to write
a condition which will be true if the width is invalid:
( (width < MIN_WIDTH) || (width > MAX_WIDTH) )
- note the profuse use of brackets. You must put these in.
Complete Glazing Program
This is a complete solution to the glazing problem. It uses all the tricks
mentioned above, plus a few which are covered below.
/* Complete Double Glazing Program */
/* Rob Miles Nov. 1990 */
#include <stdio.h>
/* Define our window size range */
#define MAX_HEIGHT 3.0
#define MAX_WIDTH 5.0
#define MIN_HEIGHT 0.75
#define MIN_WIDTH 0.5
/* Define a few costs */
#define COST_TO_MAKE 2.00
#define WOOD_COST 2.00
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming
C Programming

Contenu connexe

Tendances

Agentless Monitoring with AdRem Software's NetCrunch 7
Agentless Monitoring with AdRem Software's NetCrunch 7Agentless Monitoring with AdRem Software's NetCrunch 7
Agentless Monitoring with AdRem Software's NetCrunch 7Hamza Lazaar
 
Office Enterprise2007 Product Guide
Office Enterprise2007 Product GuideOffice Enterprise2007 Product Guide
Office Enterprise2007 Product Guideguesteb5fd7f
 
Mongouk talk june_18
Mongouk talk june_18Mongouk talk june_18
Mongouk talk june_18Skills Matter
 
Share point configuration guidance for 21 cfr part 11 compliance
Share point configuration guidance for 21 cfr part 11 complianceShare point configuration guidance for 21 cfr part 11 compliance
Share point configuration guidance for 21 cfr part 11 complianceSubhash Chandra
 
Saptableref[1]
Saptableref[1]Saptableref[1]
Saptableref[1]mpeepms
 
Uni v e r si t ei t
Uni v e r si t ei tUni v e r si t ei t
Uni v e r si t ei tAnandhu Sp
 
Slalom Whitepaper - Slack v Microsoft Teams
Slalom Whitepaper -  Slack v Microsoft TeamsSlalom Whitepaper -  Slack v Microsoft Teams
Slalom Whitepaper - Slack v Microsoft Teamsdaviddrinkwine
 
Voicenger - System Requirements Specification
Voicenger - System Requirements SpecificationVoicenger - System Requirements Specification
Voicenger - System Requirements SpecificationVlad Petre
 
Hacker Academy Training Catalogue
Hacker Academy Training CatalogueHacker Academy Training Catalogue
Hacker Academy Training CatalogueHacker Academy
 
Sap system-measurement-guide
Sap system-measurement-guideSap system-measurement-guide
Sap system-measurement-guideotchmarz
 
QBD_1464843125535 - Copy
QBD_1464843125535 - CopyQBD_1464843125535 - Copy
QBD_1464843125535 - CopyBhavesh Jangale
 
Blue Doc User Manual
Blue Doc   User ManualBlue Doc   User Manual
Blue Doc User Manualgueste2804e
 
BI Project report
BI Project reportBI Project report
BI Project reporthlel
 

Tendances (19)

Lab4_Report_460
Lab4_Report_460Lab4_Report_460
Lab4_Report_460
 
Agentless Monitoring with AdRem Software's NetCrunch 7
Agentless Monitoring with AdRem Software's NetCrunch 7Agentless Monitoring with AdRem Software's NetCrunch 7
Agentless Monitoring with AdRem Software's NetCrunch 7
 
Office Enterprise2007 Product Guide
Office Enterprise2007 Product GuideOffice Enterprise2007 Product Guide
Office Enterprise2007 Product Guide
 
Python
PythonPython
Python
 
Mongouk talk june_18
Mongouk talk june_18Mongouk talk june_18
Mongouk talk june_18
 
Share point configuration guidance for 21 cfr part 11 compliance
Share point configuration guidance for 21 cfr part 11 complianceShare point configuration guidance for 21 cfr part 11 compliance
Share point configuration guidance for 21 cfr part 11 compliance
 
Saptableref[1]
Saptableref[1]Saptableref[1]
Saptableref[1]
 
Cube_it!_software_report_for_IMIS
Cube_it!_software_report_for_IMISCube_it!_software_report_for_IMIS
Cube_it!_software_report_for_IMIS
 
Uni v e r si t ei t
Uni v e r si t ei tUni v e r si t ei t
Uni v e r si t ei t
 
Slalom Whitepaper - Slack v Microsoft Teams
Slalom Whitepaper -  Slack v Microsoft TeamsSlalom Whitepaper -  Slack v Microsoft Teams
Slalom Whitepaper - Slack v Microsoft Teams
 
Voicenger - System Requirements Specification
Voicenger - System Requirements SpecificationVoicenger - System Requirements Specification
Voicenger - System Requirements Specification
 
Hacker Academy Training Catalogue
Hacker Academy Training CatalogueHacker Academy Training Catalogue
Hacker Academy Training Catalogue
 
Sap system-measurement-guide
Sap system-measurement-guideSap system-measurement-guide
Sap system-measurement-guide
 
QBD_1464843125535 - Copy
QBD_1464843125535 - CopyQBD_1464843125535 - Copy
QBD_1464843125535 - Copy
 
Blue Doc User Manual
Blue Doc   User ManualBlue Doc   User Manual
Blue Doc User Manual
 
Fbiht71598909167
Fbiht71598909167Fbiht71598909167
Fbiht71598909167
 
BI Project report
BI Project reportBI Project report
BI Project report
 
Modbuspollmanual
ModbuspollmanualModbuspollmanual
Modbuspollmanual
 
Data guard
Data guardData guard
Data guard
 

En vedette

Introduction C Programming
Introduction C ProgrammingIntroduction C Programming
Introduction C Programmingrattanano
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)Dushmanta Nath
 
Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageAbhishek Dwivedi
 

En vedette (9)

C Lecture
C LectureC Lecture
C Lecture
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Introduction C Programming
Introduction C ProgrammingIntroduction C Programming
Introduction C Programming
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C ppt
C pptC ppt
C ppt
 
C language ppt
C language pptC language ppt
C language ppt
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 

Similaire à C Programming

Aplplication server instalacion
Aplplication server instalacionAplplication server instalacion
Aplplication server instalacionhkaczuba
 
Easttom C. Computer Security Fundamentals 3ed 2016.pdf
Easttom C. Computer Security Fundamentals 3ed 2016.pdfEasttom C. Computer Security Fundamentals 3ed 2016.pdf
Easttom C. Computer Security Fundamentals 3ed 2016.pdfJarellScott
 
The Global Military IT, Data and Computing Market 2014 2024 - Extract
The Global Military IT, Data and Computing Market 2014   2024 - ExtractThe Global Military IT, Data and Computing Market 2014   2024 - Extract
The Global Military IT, Data and Computing Market 2014 2024 - ExtractSDIAPAC
 
pdf of R for Cloud Computing
pdf of R for Cloud Computing pdf of R for Cloud Computing
pdf of R for Cloud Computing Ajay Ohri
 
ProjectCodeMeter Pro Users Manual
ProjectCodeMeter Pro Users ManualProjectCodeMeter Pro Users Manual
ProjectCodeMeter Pro Users Manualasdfgarfgqr
 
oracle10g datagurad
oracle10g dataguradoracle10g datagurad
oracle10g dataguradNst Tnagar
 
Networking Notes For DIT Part 1
Networking Notes For DIT Part 1Networking Notes For DIT Part 1
Networking Notes For DIT Part 1Mehran Khan
 
Dw guide 11 g r2
Dw guide 11 g r2Dw guide 11 g r2
Dw guide 11 g r2sgyazuddin
 
Ecdl v5 module 1 print
Ecdl v5 module 1 printEcdl v5 module 1 print
Ecdl v5 module 1 printMichael Lew
 
Mateti tcpip-cnh
Mateti tcpip-cnhMateti tcpip-cnh
Mateti tcpip-cnhabhijit.tec
 
User manual for Well Plotter 1.0
User manual for Well Plotter 1.0User manual for Well Plotter 1.0
User manual for Well Plotter 1.0HydroOffice.org
 
Informatica installation guide
Informatica installation guideInformatica installation guide
Informatica installation guidecbosepandian
 
White Paper: Indoor Positioning in Offices & Smart Buildings
White Paper: Indoor Positioning in Offices & Smart BuildingsWhite Paper: Indoor Positioning in Offices & Smart Buildings
White Paper: Indoor Positioning in Offices & Smart Buildingsinfsoft GmbH
 
Aix student guide system administrations part 2 problem determination
Aix student guide system administrations part 2   problem determinationAix student guide system administrations part 2   problem determination
Aix student guide system administrations part 2 problem determinationYogesh Sharma
 
Intrusion Detection on Public IaaS - Kevin L. Jackson
Intrusion Detection on Public IaaS  - Kevin L. JacksonIntrusion Detection on Public IaaS  - Kevin L. Jackson
Intrusion Detection on Public IaaS - Kevin L. JacksonGovCloud Network
 
Ps Edms Architectural Overview
Ps Edms Architectural OverviewPs Edms Architectural Overview
Ps Edms Architectural OverviewSami Abu Shawarib
 

Similaire à C Programming (20)

Comerv3 1-12(2)
Comerv3 1-12(2)Comerv3 1-12(2)
Comerv3 1-12(2)
 
Aplplication server instalacion
Aplplication server instalacionAplplication server instalacion
Aplplication server instalacion
 
Easttom C. Computer Security Fundamentals 3ed 2016.pdf
Easttom C. Computer Security Fundamentals 3ed 2016.pdfEasttom C. Computer Security Fundamentals 3ed 2016.pdf
Easttom C. Computer Security Fundamentals 3ed 2016.pdf
 
Oracle10g new features
Oracle10g new featuresOracle10g new features
Oracle10g new features
 
The Global Military IT, Data and Computing Market 2014 2024 - Extract
The Global Military IT, Data and Computing Market 2014   2024 - ExtractThe Global Military IT, Data and Computing Market 2014   2024 - Extract
The Global Military IT, Data and Computing Market 2014 2024 - Extract
 
pdf of R for Cloud Computing
pdf of R for Cloud Computing pdf of R for Cloud Computing
pdf of R for Cloud Computing
 
Final Report - v1.0
Final Report - v1.0Final Report - v1.0
Final Report - v1.0
 
ProjectCodeMeter Pro Users Manual
ProjectCodeMeter Pro Users ManualProjectCodeMeter Pro Users Manual
ProjectCodeMeter Pro Users Manual
 
oracle10g datagurad
oracle10g dataguradoracle10g datagurad
oracle10g datagurad
 
Networking Notes For DIT Part 1
Networking Notes For DIT Part 1Networking Notes For DIT Part 1
Networking Notes For DIT Part 1
 
Dw guide 11 g r2
Dw guide 11 g r2Dw guide 11 g r2
Dw guide 11 g r2
 
Ecdl v5 module 1 print
Ecdl v5 module 1 printEcdl v5 module 1 print
Ecdl v5 module 1 print
 
Mateti tcpip-cnh
Mateti tcpip-cnhMateti tcpip-cnh
Mateti tcpip-cnh
 
User manual for Well Plotter 1.0
User manual for Well Plotter 1.0User manual for Well Plotter 1.0
User manual for Well Plotter 1.0
 
Master's Thesis
Master's ThesisMaster's Thesis
Master's Thesis
 
Informatica installation guide
Informatica installation guideInformatica installation guide
Informatica installation guide
 
White Paper: Indoor Positioning in Offices & Smart Buildings
White Paper: Indoor Positioning in Offices & Smart BuildingsWhite Paper: Indoor Positioning in Offices & Smart Buildings
White Paper: Indoor Positioning in Offices & Smart Buildings
 
Aix student guide system administrations part 2 problem determination
Aix student guide system administrations part 2   problem determinationAix student guide system administrations part 2   problem determination
Aix student guide system administrations part 2 problem determination
 
Intrusion Detection on Public IaaS - Kevin L. Jackson
Intrusion Detection on Public IaaS  - Kevin L. JacksonIntrusion Detection on Public IaaS  - Kevin L. Jackson
Intrusion Detection on Public IaaS - Kevin L. Jackson
 
Ps Edms Architectural Overview
Ps Edms Architectural OverviewPs Edms Architectural Overview
Ps Edms Architectural Overview
 

Plus de Sudharsan S (20)

Xml1111
Xml1111Xml1111
Xml1111
 
Xml11
Xml11Xml11
Xml11
 
Xml plymouth
Xml plymouthXml plymouth
Xml plymouth
 
Xml Presentation-3
Xml Presentation-3Xml Presentation-3
Xml Presentation-3
 
Xml Presentation-1
Xml Presentation-1Xml Presentation-1
Xml Presentation-1
 
XML Presentation-2
XML Presentation-2XML Presentation-2
XML Presentation-2
 
Xml
XmlXml
Xml
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Unix
UnixUnix
Unix
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 
Unix
UnixUnix
Unix
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C Introduction
C IntroductionC Introduction
C Introduction
 
College1
College1College1
College1
 
Preface
PrefacePreface
Preface
 
Toc Sg
Toc SgToc Sg
Toc Sg
 
Les08
Les08Les08
Les08
 
Les06
Les06Les06
Les06
 
Les07
Les07Les07
Les07
 
Les04
Les04Les04
Les04
 

Dernier

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 

Dernier (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 

C Programming

  • 1. Introduction to C Programming Rob Miles Department of Computer Science
  • 2. i Contents Computers 1 An Introduction to Computers........................................................................................1 Hardware and Software ....................................................................................1 Data and Information .......................................................................................2 Data Processing................................................................................................2 Programming Languages 4 What is Programming? ..................................................................................................4 From Problem to Program ................................................................................5 Programming Languages ...............................................................................................8 C 8 A look at C ....................................................................................................................8 Making C Run..................................................................................................9 Creating C Programs........................................................................................9 What Comprises a C Program?.......................................................................10 The Advantages of C......................................................................................11 The Disadvantages of C..................................................................................11 A First C Program 11 The Program Example .................................................................................................11 #include ........................................................................................................12 <stdio.h>.......................................................................................................12 void ...............................................................................................................12 main ..............................................................................................................13 ( void )...........................................................................................................13 { .....................................................................................................................13 float ...............................................................................................................13 height, width, area, wood_length................................................................13 ; .....................................................................................................................14 scanf .............................................................................................................14 ( .....................................................................................................................14 "%f", ..............................................................................................................14 &height..........................................................................................................15 ) ;...................................................................................................................15 scanf ( "%f", &width ) ;.................................................................................15 area = 2 * height * width ;............................................................................15 wood_length = 2 * ( height + width ) * 3.25 ;.................................................16 printf..............................................................................................................16 ( "The area of glass needed is : %f metres.n",.........................................16 area ) ; ..........................................................................................................17 printf ( "The length of wood needed is : %f feet.n", wood_length ) ; ......17 } .....................................................................................................................17 Punctuation ....................................................................................................17 Variables 18
  • 3. ii Variables and Data.........................................................................................18 Types of Variables .......................................................................................................18 Declaration ..................................................................................................................18 int variables....................................................................................................19 float variables ................................................................................................19 char variables ................................................................................................19 Missing Types................................................................................................19 Variable Declaration....................................................................................................19 Giving Values to Variables ..........................................................................................20 Expressions....................................................................................................21 Types of Data in Expressions..........................................................................22 Getting Values into the Program..................................................................................23 Writing a Program 24 Comments......................................................................................................24 Program Flow ..............................................................................................................24 Conditional Execution - if...............................................................................25 Conditions and Relational Operators ..............................................................26 Combining Logical Operators.........................................................................27 Lumping Code Together.................................................................................27 Magic Numbers and #define..........................................................................28 Loops .............................................................................................................29 Breaking Out of Loops ...................................................................................32 Going Back to the Top of a Loop....................................................................32 More Complicated Decisions..........................................................................33 Complete Glazing Program ............................................................................33 Operator Shorthand........................................................................................34 Statements and Values....................................................................................35 Neater Printing...............................................................................................36 Functions 37 Functions So Far..........................................................................................................37 Function Heading...........................................................................................37 Function Body................................................................................................38 return .............................................................................................................38 Calling a Function..........................................................................................38 Scope .............................................................................................................39 Variables Local to Blocks...............................................................................40 Full Functions Example..................................................................................40 Pointers........................................................................................................................42 NULL Pointers...............................................................................................44 Pointers and Functions ...................................................................................44 Static Variables............................................................................................................45 Arrays 46 Why We Need Arrays ..................................................................................................46 Sorting ...........................................................................................................47 Array Types and Sizes..................................................................................................49 More Than One Dimension............................................................................50 Switching 53 Making Multiple Decisions..........................................................................................53 Strings 55
  • 4. iii How long is a piece of string?.......................................................................................55 Putting Values into Strings ..........................................................................................56 Using Strings...............................................................................................................57 The String Library .......................................................................................................58 strcpy .............................................................................................................59 strcmp............................................................................................................59 strlen..............................................................................................................59 Reading and Printing Strings .......................................................................................59 Bomb Proof Input.........................................................................................................60 Structures 61 What is a Structure?.....................................................................................................61 How Structures Work...................................................................................................63 Pointers to structures....................................................................................................63 Defining your own Types .............................................................................................64 Files 65 When do we use Files?.................................................................................................65 Streams and Files ...........................................................................................65 fopen and fclose ...........................................................................................................66 Mode String ...................................................................................................68 File Functions ..............................................................................................................70 fread and fwrite..............................................................................................70 The End of the File and Errors.....................................................................................71 Memory 72 Fetching Memory.........................................................................................................72 malloc ............................................................................................................72 free.................................................................................................................73 The heap......................................................................................................................73 C and Large Programs 74 Building Large Programs in C .....................................................................................74 The Compile and Link Process.......................................................................74 Referring to External Items ............................................................................75 The Make Program.........................................................................................76 Projects ..........................................................................................................76 The C Pre-Processor.....................................................................................................77 The #include Directive ...................................................................................77 Conditional Compilation ................................................................................77 A Sample Project .........................................................................................................78 The Problem...................................................................................................78 The Data Structure .........................................................................................78 Program Files.................................................................................................79 The Most Important Bit!.................................................................................84 Glossary of Terms 93 Index 95 This document is © Rob Miles 2001 Department of Computer Science, The University of Hull All rights reserved. No reproduction, copy or transmission of this publication may be made without written permission.
  • 5. iv The author can be contacted at: The Department of Computer Science, The University of Hull, HULL, HU6 7RX r.s.miles@dcs.hull.ac.uk
  • 6. Computers ? 1 Computers An Introduction to Computers Qn: Why does a bee hum? Ans: Because it doesn't know the words! One way of describing a computer is as an electric box which humms. This, whilst technically correct, can lead to significant amounts of confusion, particularly amongst those who then try to program a fridge. A better way is to describe it as: A device which processes information according to instructions it has been given. This general definition rules out fridges but is not exhaustive. However for our purposes it will do. The instructions you give to the computer are often called a program. The business of using a computer is often called programming. This is not what most people do with computers. Most users do not write programs, instead they talk to programs written by other people. We must therefore make a distinction between users and programmers. A user has a job which he or she finds easier to do on a computer running the appropriate program. A programmer has a masochistic desire to tinker with the innards of the machine. One of the golden rules is that you never write your own program if there is already one available, i.e. a keen desire to process words with a computer should not result in you writing a word processor! However, because you will often want to do things with computers which have not been done before, and further because there are people willing to pay you to do it, we are going to learn how to program as well as use a computer. Before we can look at the fun packed business of programming though it is worth looking at some computer terminology: Hardware and Software If you ever buy a computer you are not just getting a box which humms. The box, to be useful, must also have sufficient built in intelligence to understand simple commands to do things. At this point we must draw a distinction between the software of a computer system and the hardware. Hardware is the physical side of the system. Essentially if you can kick it, and it stops working when immersed in a bucket of water, it is hardware. Hardware is the impressive pile of lights and switches in the corner.... Software is what makes the machine tick. If a computer has a soul it keeps it in its software. Software uses the physical ability of the hardware, which can run programs, do something useful. It is called software because it has no physical
  • 7. Computers ? 2 existence and it is comparatively easy to change. Software is the voice which says "Computer Running" in a Star Trek film. We are going to use an operating system called MS- DOS. Later we will be using UNIX. All computers are sold with some software. Without it they would just be a novel and highly expensive heating system. The software which comes with a computer is often called its Operating System. The Operating System makes the machine usable. It looks after all the information held on the computer and provides lots of commands to allow you to manage things. It also lets you run programs, ones you have written and ones from other people. You will have to learn to talk to an operating system so that you can create your C programs and get them to go. Data and Information People use the words data and information interchangeably. They seem to think that one means the other. I regard data and information as two different things: Data is the collection of ons and offs which computers store and manipulate. Information is the interpretation of the data by people to mean something. Strictly speaking computers process data, humans work on information. An example, the computer holds the bit pattern: 11111111 11111111 11111111 00000000 However you could regard this as meaning: "you are 256 pounds overdrawn at the bank" or "you are 256 feet below the surface of the ground" or "eight of the thirty two light switches are off" The transition from data to information is usually made when the human reads the output. So why am I being so pedantic? Because it is vital to remember that a computer does not "know" what the data it is processing actually means. As far as it is concerned data is just patterns of bits, it is you who gives meaning to these patterns. Remember this when you get a bank statement which says that you have £8,388,608! Data Processing Computers are data processors. Information is fed into them, they do something with it, and then generate further information. A computer program tells the computer what to do with the information coming in. A computer works on data in the same way that a sausage machine works on meat, something is put in one end, some processing is performed, and something comes out of the other end: Data Computer Data This makes a computer a very good "mistake amplifier", as well as a useful thing to blame..... A program is unaware of the data it is processing in the same way that a sausage machine is unaware of what meat is. Put a bicycle into a sausage machine and it will try to make sausages out of it. Put duff data into a computer and it will do equally useless things. It is only us people who actually ascribe meaning to data (see above), as far a the computer is concerned it is just stuff coming in which has to be manipulated in some way.
  • 8. Computers ? 3 A computer program is just a sequence of instructions which tell a computer what to do with the data coming in, and what form the data sent out will have. Note that the data processing side of computers, which you might think is entirely reading and writing numbers, is much more than that, examples of typical data processing applications are: Digital Watch : A micro-computer in your watch is taking pulses from a crystal and requests from buttons, processing this data and producing a display which tells you the time. Car : A micro-computer in the engine is taking information from sensors telling it the current engine speed, road speed, oxygen content of the air, setting of the accelerator etc and producing voltages out which control the setting of the carburettor, timing of the spark etc, to optimise the performance of the engine. CD Player : A computer is taking a signal from the disk and converting it into the sound that you want to hear. At the same time it is keeping the laser head precisely positioned and also monitoring all the buttons in case you want to select another part of the disk. Note that some of these data processing applications are merely applying technology to existing devices to improve the way they work. However one, the CD player, could not be made to work without the built-in data processing ability. Most reasonably complex devices contain data processing components to optimise their performance and some exist only because we can build in intelligence. It is into this world that we, as software writers are moving. It is important to think of business of data processing as much more than working out the company payroll, reading in numbers and printing out results. These are the traditional uses of computers. Note that this "raises the stakes" in that the consequences of software failing could be very damaging. As engineers it is inevitable that a great deal of our time will be spent fitting data processing components into other devices to drive them. You will not press a switch to make something work, you will press a switch to tell a computer to make it work. These embedded systems will make computer users of everybody, and we will have to make sure that they are not even aware that there is a computer in there!
  • 9. Programming Languages ? 4 Programming Languages What is Programming? I tell people I am a "Software Engineer". Programming is a black art. It is the kind of thing that you grudgingly admit to doing, at night, with the blinds drawn and nobody watching. Tell people that you program computers and you will get one of the following responses: 1. A blank stare. 2. "That's interesting", followed by a long description of the double glazing that they have just had fitted. 3. "My younger brother has a Sinclair Spectrum. He's a programmer as well." 4. A look which indicates that you can't be a very good one as they all drive Ferraris and tap into the Bank of England at will. Programming is defined by most people as earning huge sums of money doing something which nobody can understand. Programming is defined by me as deriving and expressing a solution to a given problem in a form which a computer system can understand and execute. One or two things fall out of this definition: ? You need to be able to solve the problem yourself before you can write a program to do it. ? The computer has to be made to understand what you are trying to tell it to do. We are back to the term "Software Engineer" again! I like to think of a programmer as a bit like a plumber! A plumber will arrive at a job with a big bag of tools and spare parts. Having looked at it for a while, tut tutting, he will open his bag and produce various tools and parts, fit them all together and solve your problem. Programming is just like this. You are given a problem to solve. You have at your disposal a big bag of tricks, in this case a programming language. You look at the problem for a while and work out how to solve it and then fit the bits of the language together to solve the problem you have got. The art of programming is knowing which bits you need to take out of your bag of tricks to solve each part of the problem.
  • 10. Programming Languages ? 5 From Problem to Program Programming is not about mathematics, it is about organisation. The art of taking a problem and breaking it down into a set of instructions you can give a computer is the interesting part of programming. Unfortunately it is also the most difficult part of programming as well. If you think that learning to program is simply a matter of learning a programming language you are very wrong. In fact if you think that programming is simply a matter of coming up with a program which solves a problem you are equally wrong! There are many things you must consider when writing a program; not all of them are directly related to the problem in hand. I am going to start on the basis that you are writing your programs for a customer. He or she has problem and would like you to write a program to solve it. We shall assume that the customer knows even less about computers than we do! Initially we are not even going to talk about the programming language, type of computer or anything like that, we are simply going to make sure that we know what the customer wants. Coming up with a perfect solution to a problem the customer has not got is something which happens surprisingly often in the real world. The worst thing you can say to a customer is "I can do that". Instead you should think "Is that what the customer wants?". This is almost a kind of self discipline. Programmers pride themselves on their ability to come up with solutions, so as soon as they are given a problem they immediately start thinking of ways to solve it, this almost a reflex action. What you should do is think "Do I really understand what the problem is?". Before you solve a problem you should make sure that you have a watertight definition of what the problem is, which both you and the customer agree on. In the real world this is often called a Functional Design Specification or FDS. This tells you exactly what the customer wants. Both you and the customer sign it, and the bottom line is that if you provide a system which behaves according to the design specification the customer must pay you. Once you have got your design specification, then you can think about ways of solving the problem. You might think that this is not necessary if you are writing a program for yourself; there is no customer to satisfy. This is not true. Writing an FDS forces you to think about your problem at a very detailed level. A Simple Problem Consider the scenario; You are sitting in your favourite chair in the pub contemplating the universe when you are interrupted in your reverie by a friend of yours who sells double glazing for a living. He knows you are a programmer of sorts and would like your help in solving a problem which he has: He has just started making his own window units and is looking for a program which will do the costing of the materials for him. He wants to just enter the dimensions of the window and then get a print out of the cost to make the window, in terms of the amount of wood and glass required. "This looks like a nice little earner" you think, and once you have agreed a price you start work. The first thing you need to do is find out exactly what the customer wants you to do... Specifying the Problem When considering how to write the specification of a system there are three important things : ? What information flows into the system. ? What flows out of the system. ? What the system does with the information.
  • 11. Programming Languages ? 6 There are lots of ways of representing this information in the form of diagrams, for now we will stick with written text when specifying each of the stages: Information going in In the case of our immortal double glazing problem we can describe the information as: ? The width of a window. ? The height of the window. Information coming out The information that our customer wants to see is : ? the area of glass required for the window ? the length of wood required to build a frame. What the program actually does The program can derive the two values according to the following equations : glass area = width of window * height of window wood length = (width of window + height of window) * 2 Putting in more detail We now have a fairly good understanding of what our program is going to do for us. Being sensible and far thinking people we do not stop here, we now have to worry about how our program will decide when the information coming in is actually valid. This must be done in conjunction with the customer, he or she must understand that if information is given which fits within the range specified, your program will regard the data as valid and act accordingly. In the case of the above we could therefore expand the definition of data coming in as : ? The width of the window, in metres and being a value between 0.5 Metres and 3.5 metres inclusive. ? The height of the window, in metres and being a value between 0.5 metres and 2.0 metres inclusive. Note that we have also added units to our description, this is very important - perhaps our customer buys wood from a supplier who sells by the foot, in which case our output description should read : ? The area of glass required for the window, in square metres. ? The length of wood required for the frame, given in feet using the conversion factor of 3.25 feet per metre. Note that both you and the customer must understand the document! Having written this all up in a form that both you and the customer can understand, we must then both sign the completed specification, and work can commence. In a real world you would now create a procedure which will allow you to prove that the program works, you could for example say : If I give the above program the inputs 2 metres high and 1 metre wide the program should print out : 2 square metres of glass and 9.75 feet of wood. The test procedure which is designed for a proper project should test out all possible states within the program, including the all important error conditions.
  • 12. Programming Languages ? 7 In a large system the person writing the program may have to create a test harness which is fitted around the program and will allow it to be tested. Both the customer and the supplier should agree on the number and type of the tests to be performed and then sign a document describing these. Better yet, set up a phased payment system so that you get some money as the system is developed. At this point the supplier knows that if a system is created which will pass all the tests the customer has no option but to pay him for the work! Note also that because the design and test procedures have been frozen, there is no ambiguity which can lead to the customer requesting changes to the work although of course this can still happen! Note also in a "proper" system the customer will expect to be consulted as to how the program will interact with the user, sometimes even down to the colour of the letters on the display! Remember that one of the most dangerous things that a programmer can think is "This is what he wants"! The precise interaction with the user - what the program does when an error is encountered, how the information is presented etc., is something which the customer is guaranteed to have strong opinions about. Ideally all this information should be put into the specification, which should include layouts of the screens and details of which keys should be pressed at each stage. Fact: If you expect to derive the specification as the project goes on either you will fail to do the job, or you will end up performing five times the work! If this seems that you are getting the customer to help you write the program then you are exactly right! Your customer may have expected you to take the description of the problem and go into your back room - to emerge later with the perfect solution to the problem. This is not going to happen. What will happen is that you will come up with something which is about 60% right. The customer will tell you which bits look OK and which bits need to be changed. You then go back into your back room, muttering under your breath, and emerge with another system to be approved. Again, Robert's law says that 60% of the duff 40% will now be OK, so you accept changes for the last little bit and again retreat to your keyboard.... The customer thinks that this is great, reminiscent of a Saville Row tailor who produces the perfect fit after numerous alterations. All the customer does is look at something, suggests changes and then wait for the next version to find something wrong with..... Fact: More implementations fail because of inadequate specification than for any other reason! If your insisting on a cast iron specification forces the customer to think about exactly what the system is supposed to do and how it will work, all to the better. The customer may well say "But I am paying you to be the computer expert, I know nothing about these machines". This is no excuse. Explain the benefits of "Right First Time" technology and if that doesn't work produce a revolver and force the issue! Again, if I could underline in red I would : All the above apply if you are writing the program for yourself. You are your own worst customer! You may think that I am labouring a point here, the kind of simple systems we are going to create as we learn to program are going to be so trivial that the above techniques are far too long winded. You are wrong. One very good reason for doing this kind of thing is that it gets most of the program written for you - often with the help of the customer. When we start with our double glazing program we now know that we have to : read in the width verify the value read in the height verify the value calculate width times height and print it calculate ( width + height ) * 2 * 3.35 and print it The programming portion of the job is now simply converting the above description into a language which can be used in a computer.......
  • 13. C ? 8 Programming Languages You might ask the question "Why do we need programming languages, why can we not use something like English?" There are two answers to this one: 1. Computers are too stupid to understand English. 2. English would make a lousy programming language. Please note that this does not imply that tape worms would make good programmers! To take the first point. We cannot make very clever computers at the moment. Computers are made clever by putting software into them, and there are limits to the size of program that we can create and the speed at which it can talk to us. At the moment, by using the most advanced software and hardware, we can make computers which are about as clever as a tape worm. Tape worms do not speak very good English, therefore we cannot make a computer which can understand English. The best we can do is get a computer to make sense of a very limited language which we use to tell it what to do. Time Files like an Arrow. Fruit Flies like a Banana! To take the second point. English as a language is packed full of ambiguities. It is very hard to express something in an unambiguous way using English, if you do not believe me, ask any lawyer! Programming languages get around both of these problems. They are simple enough to be made sense of by computer programs and they reduce ambiguity. There are very many different programming languages around, you will need to know more than one if you are to be a good programmer. C A look at C There are literally hundreds of programming languages around, you will need to know at least 3! We are going to learn a language called C. C is a very flexible and powerful programming language originally designed in the early 1970s. It is famous as the language the UNIX operating system was written in, and was specially designed for this. However its use has now spread way beyond that field and it is currently very popular. C is a professional language. So what do I mean by that? Consider the chain saw. If I, Rob Miles, want to use a chain saw I will hire one from a shop. As I am not an experienced chain saw user I would expect it to come with lots of built in safety features such as guards and automatic cut outs. These will make me much safer with the thing but will probably limit the usefulness of the tool, i.e. because of all the safety stuff I might not be able to cut down certain kinds of tree. If I was a real lumberjack I would go out and buy a professional chain saw which has no safety features whatsoever but can be used to cut down most anything. If I make a mistake with the professional tool I could quite easily lose my leg, something the amateur machine would not let happen.
  • 14. C ? 9 In programming terms this means is that C lacks some safety features provided by other programming languages. This makes the language much more flexible. However, if I do something stupid C will not stop me, so I have a much greater chance of crashing the computer with a C program than I do with a safer language. This is not something to worry about, you should always work on the basis that any computer will tolerate no errors on my part and anything that I do which is stupid will always cause a disaster! Making C Run You actually write the program using some form of text editor - which may be part of the compiling and linking system. C is usually a compiled programming language. The computer cannot understand the language directly, so a program called a compiler converts the C into the machine code instructions which do the job. Actually getting a program to run is however a two stage process. First you show your program, often called the source, to the compiler. If the compiler gives it the thumbs up you then perform a process called linking. Linking is when all the various portions of your program are brought together to form something which can be run. You might ask "Why to we link things? - the compiler has created a machine code version of my program, can't I just run that?". The reason that we have the additional linking process is that it allows us to reuse standard pieces of code from a library. Many things your program will do are common to lots of other programs, for example you will want to read information from the keyboard and you will want to send information to the display. Rather than compile the program code which does this every time you compile your program, a much more efficient way is to put a compiled version of this code into a library. Your program just contains a reference to the particular function you want to use, the linker then loads the relevant part from the library when it creates your program. It is possible to get the compiler to give you warnings in this case. Note that a side effect of this is that if you refer to a function which does not exist, the compiler will not mind particularly - but the linker will not find the item in its library, and thus give you an error. Once the linker has finished you are left with a free standing file which is your program. If you run this your program gets control! Creating C Programs The actual business of constructing and compiling the depends on the computer you are using and the particular version of C. We will look at the business of producing your program in the laboratory section of this course. Initially it is best if we just work through your programs on paper. I reckon that you write programs best when you are not sitting at the computer, i.e. the best approach is to write (or at least map out) your solution on paper a long way away from the machine. Once you are sitting in front of the keyboard there is a great temptation to start pressing keys and typing something in which might work. This is not good technique. You will almost certainly end up with something which almost works, which you will then spend hours fiddling with to get it going. If you had sat down with a pencil and worked out the solution first you would probably get to a working system in around half the time. I am not impressed by hacking programmers who spend whole days at terminals fighting with enormous programs and debugging them into shape. I am impressed by someone who turns up, types in the program and makes it work first time!
  • 15. C ? 10 What Comprises a C Program? A program is the thing that you write to perform a particular task. It will actually be a file of text, often called a source file. This is what the compiler acts on. A source file contains three things : ? instructions to the compiler ? information about the structures which will hold the data to be stored and manipulated. ? instructions which manipulate the data. To take these in turn Controlling the Compiler The compiler directives are the same for all versions of C. One of the very powerful features of C is the way in which you can change the way the compiler processes your program by including directives. There are many directives available, in a C program a directive is always preceded by the # character and must appear right at the beginning of a line. Directives can be used to "build in" particular values, for example constants like PI, and also allow you to change which parts of the program which the compiler works on, making it possible to use the same piece of program on several different types of computer. Storing the Data Programs work by processing data. The data has to be stored within the computer whilst the program processes it. All computer languages support variables of one form or another. A variable is simply a named location in which a value is held whilst the program runs. C also lets you build up structures which can hold more than one item, for example a single structure could hold all the information about a particular bank customer. Describing the Solution The actual instructions which describe your solution to the problem must also be part of your program. In the case of C a lump of program which does one particular thing is called a function. Seasoned programmers break down a problem into a number of smaller ones and make a function for each. A function can be very small, or very large. It can return a value which may or may not be of interest. It can have any name you like, and your program can contain as many functions as you see fit. One function may refer to others. The C language also has a large number of function libraries available which you can use. These save you from "re-inventing the wheel" each time you write a program. Within the function there will be a number of statements. A statement is an instruction to perform one particular operation, for example add two numbers together and store the result. The really gripping thing about programs is that a statement can decide which statement is performed next, so that your program can look at things and decide what to do. You give a name to each function that you create, and you try to make the name of the function fit what it does, for example menu or save_file. The C language actually runs your program by looking for a function with a special name, main. This function is called when your program starts running, and when main finishes, your program ends.
  • 16. A First C Program ? 11 The Advantages of C The good news about C is that you can write code which runs quickly, and your program is very "close to the hardware". By that I mean that you can access low level facilities in your computer quite easily, without the compiler or run time system stopping you from doing something potentially dangerous. The use of compiler directives to the pre-processor make it possible to produce a single version of a program which can be compiled on several different types of computer. In this sense C is said to be very portable. The function libraries are standard for all versions of C so they can be used on all systems. The Disadvantages of C The disadvantages of C fall neatly from the advantages. The biggest one is that you can write C programs which can fail in very catastrophic ways. These programs will appear totally valid as far as the compiler is concerned but will not work and may even cause your computer to stop. A more picky language would probably notice that you were doing something stupid in your program and allow you to find the error before it crashed your computer! However a more picky language would probably not allow you to write the program in the first place! Another disadvantage of C is that it allows you to write very terse code. You can express exactly what you want to do in very few statements. You might think that this is nice, because it makes your programs even more efficient, but it has the side effect of making them much harder to understand. At the time you write the code you know exactly what each part is supposed to do. If you come back to the program in several months you will need time to "get back inside it". If the code is written very tightly you will take much longer to do this, and other people may not be able to understand it at all! I write code which is not the most efficient possible, but is easy to understand. I am sacrificing program performance for ease of maintenance. A First C Program 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:
  • 17. A First C Program ? 12 #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? #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. (see later) <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 Some C programs have the type of int so that the main function can return a value to the operating system which runs it. We are not going to do this. 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.
  • 18. A First C Program ? 13 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
  • 19. A First C Program ? 14 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.
  • 20. A First C Program ? 15 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.
  • 21. A First C Program ? 16 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 : Format Command %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.
  • 22. A First C Program ? 17 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 #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 metr es.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....
  • 23. Variables ? 18 Variables Variables and Data Programs operate on data. A programming language must give you a way of storing the data you are processing, otherwise it is useless. What the data actually means is something that you as programmer decide (see above digression on data). Types of Variables Basically there are two types of data: ? Nice chunky individual values, for example the number of sheep in a field, teeth on a cog, apples in a basket. ? Nasty real world type things, for example the current temperature, the length of a piece of string, the speed of a car. In the first case we can hold the value exactly; you always have an exact number of these items, they are integral. When you are writing a specification you should worry about the precision to which values are to be held. Too much accuracy may slow the machine down - too little may result in the wrong values being used. In the second case we can never hold what we are looking at exactly. Even if you measure a piece of string to 100 decimal places it is still not going to give you its exact length - you could always get the value more accurately. These are real. A computer is digital, i.e. it operates entirely on patterns of bits which can be regarded as numbers. Because we know that it works in terms of ons and offs it has problems holding real values. To handle real values the computer actually stores them to a limited accuracy, which we hope is adequate (and usually is). This means that when we want to store something we have to tell the computer whether it is an integer or a real. In fact it is useful to have several types of data. Declaration Robs' Arbitrary Standard For Coloured Boxes! You tell C about something you want to store by declaring it. The declaration also identifies the type of the thing we want to store. Think of this as C creating a box of a particular size, specifically designed to hold items of the given type. We identify what type of data a particular box can hold by making it a certain colour, according to RASFCB integer boxes are coloured red and real (or floating point) boxes are coloured green.
  • 24. Variables ? 19 Note that C is often called weakly typed. This does not mean that you do not press the keys very hard (ho ho), what it means is that C does not fuss about what you put in each box. If you have a red box (of type integer), and then ask C to put a green value into it (of type real or floating point), C will not complain that what you want to do is meaningless, it will just do it. Other languages, for example PASCAL, get all hot under the collar when you try to do this, they are called strongly typed. Weakly typed languages let you do exactly what you want so, provided you know what you are doing, everything will work out OK. We will consider just three types for the moment, there are others available but you can get by with these for now: int variables Note that we can go one further negative than positive. This is because the numbers are stored using "2's complement" noation. A type of box which can hold only integer values, i.e. no fractional part. The precise range of integers which are supported varies from one version of C to another, in the version we are using it goes from -32768 to +32767 float variables A type of box which can hold a real (i.e. floating point) number. These are held to limited precision, again the precision and range you get varies from one version of C to another, in the version of C we are using it goes from 3.4E-38 to 3.4E+38. char variables A type of box which can hold a single character. We have already come across characters when we looked at filenames and the like. A character is what you get when you press a key on a keyboard. Missing Types If you are used to other languages you might think that there are some storage types missing, for example there is no way to store strings of characters. In C, unlike BASIC, you have to manage the storage of strings yourself - however there are a large number of built in facilities to make like easier. We will come to these later. Another missing type is that used to store logical values, i.e. either TRUE or FALSE. C does not provide this facility, but uses the convention throughout that 0 means false and any other value means true. There are operators that can be used to provide logical combinations in C, but they will work on any non- real data type. Variable Declaration Before you can use a particular box you have to tell the compiler about it. C will not just create boxes for you; it has to know the name of the box and what you are going to put into it. You tell C about a box by declaring it. When the compiler is given a declaration it says something along the lines of:
  • 25. Variables ? 20 Here is the name of something which we want to store. I will create a box of the type requested, paint it the correct colour and write the name on it. Later on I will put things in the box and get things out of it. I will put the box on a shelf out of the way for now. Such a box is often called a variable. All languages support different types of variables, all have types equivalent to the C ones. Remember that all we have is a box. The box is not empty at the moment, but there is nothing of interest in it; the contents are what we call undefined. If you use the contents of an undefined variable you can look forward to your program doing something different each time you run it! C paints the name on the box using a stencil. There are only a few stencils available, so the characters that you can use to name a variable are limited. Also, because of the design of the stencils themselves, there are some rules about how the names may be formed, namely: ? All variable names must start with a letter. ? After the letter you can have either letters or numbers or the underscore "_" character. The length of the name allowed depends on the version of C you are using. You can use amazingly long names in any version of C, the important thing to remember is that only a certain number of characters are looked at, i.e. very_long_and_impressive_C_variable_called_fred and very_long_amd_impressive_C_variable_called_jim - would probably be regarded as the same in most versions of C. Upper and lower case letters are different, i.e. Fred and fred are different variables. Here are a few example declarations, one of which are not valid (see if you can guess which one and why) : int fred ; float jim ; char 29yesitsme ; One of the golden rules of programming, along with "always use the keyboard with the keys uppermost" is: Always give your variables meaningful names. According to the Mills and Boon romances that I have read, the best relationships are meaningful ones. Giving Values to Variables Once we have got ourselves a variable we now need to know how to put something into it, and get the value out. C does this by means of an assignment. There are two parts to an assignment, the thing you want to assign and the place you want to put it, for example consider the following:
  • 26. Variables ? 21 void main ( void ) { int first, second, third ; first = 1 ; second = 2 ; second = second + first ; } The first part of the program should be pretty familiar by now. Within the main function we have declared three variables, first, second and third. These are each of integer type. The last three statements are the ones which actually do the work. These are assignment statements. An assignment gives a value to a specified variable, which must be of a sensible type (note that you must be sensible about this because the compiler, as we already know, does not know or care what you are doing). The value which is assigned is an expression. The equals in the middle is there mainly do confuse us, it does not mean equals in the numeric sense, I like to think of it as a gozzinta (see above). Gozzintas take the result on the right hand side of the assignment and drop it into the box on the left, which means that: 2 = second + 1 ; is a piece of programming naughtiness which would cause all manner of nasty errors to appear. Expressions An expression is something which returns a result. We can then use the result as we like in our program. Expressions can be as simple as a single value and as complex as a large calculation. They are made up of two things, operators and operands. Operands Operands are things the operators work on; They are usually constant values or the names of variables. In the program above first, second, third and 2 are all operands. Operators Operators are the things which do the work; They specify the operation to be performed on the operands. Most operators work on two operands, one each side. In the program above + is the only operator. Here are a few example expressions: 2 + 3 * 4 -1 + 3 (2 + 3) * 4 These expressions are worked out (evaluated) by C moving from left to right, just as you would yourself. Again, just as in traditional maths all the multiplication and division is performed first in an expression, followed by the addition and subtraction. C does this by giving each operator a priority. When C works out an expression it looks along it for all the operators with the highest priority and does them first. It then looks for the next ones down and so on until the final result is obtained. Note that this means that the first expression above will therefore return 14 and not 20.
  • 27. Variables ? 22 If you want to force the order in which things are worked out you can put brackets around the things you want done first, as in the final example. You can put brackets inside brackets if you want, provided you make sure that you have as many open ones as close ones. Being a simple soul I tend to make things very clear by putting brackets around everything. It is probably not worth getting too worked up about this expression evaluation as posh people call it, generally speaking things tend to be worked out how you would expect them. For completeness here is a list of all operators, what they do and their precedence (priority). I am listing the operators with the highest priority first. op. use - unary minus, the minus that C finds in negative numbers, e.g. -1. Unary means applying to only one item. * multiplication, note the use of the * rather than the more mathematically correct but confusing x. / division, because of the difficulty of drawing one number above another on a screen we use this character instead + addition, no problems here. - subtraction. Note that we use exactly the same character as for unary minus. This is not a complete list of all the operators available, but it will do for now. Because these operators work on numbers they are often called the numeric operators. Types of Data in Expressions When C performs an operator, it makes a guess as to the type of the result that is to be produced. Essentially, if the two operands are integer, it says that the result should be integer, if the two are floating point, it says that the result should be floating point. This can lead to problems, consider the following : 1/2 1/2.0 You might think that these would give the same result. Not so. The compiler thinks that the first expression, which involves only integers, should give an integer result. It therefore would calculate this to be the integer value 0 (the fractional part is always truncated). The second expression, because it involves a floating point value would however be evaluated to give a floating point result, the correct answer of 0.5 Casting We can force C to regard a value as being of a certain type by the use of casting. A cast takes the form of an additional instruction to the compiler to force it regard a value in a particular way. You cast a value by putting the type you want to see there in brackets before it. For example :
  • 28. Variables ? 23 #include <stdio.h> void main ( void ) { int i = 3, j = 2 ; float fraction ; fraction = (float) i / (float) j ; printf ( "fraction : %f n", fraction ) ; } The (float) part of the above tells the compiler to regard the values in the integer variables as floating point ones, so that we get 1.5 printed out rather than 1. When you cast, which you need to do occasionally, remember that casting does not affect the actual value, just how C regards the number. As we saw above, each type of variable has a particular range of possible values, and the range of floating point values is much greater than that for integers. This means that if you do things like : int i ; i = (int) 12345678.999 ; I do not think of this as a failing in C. It gives you great flexibility, at the cost of assuming you know what you are doing.... - the cast is doomed to fail. The value which gets placed in i will be invalid. Nowhere in C does the language check for mistakes like this. It is up to you when you write your program to make sure that you never exceed the range of the data types you are using - the program will not notice but the user certainly will! Getting Values into the Program We have used the printf (print-formatted) standard input/output procedure from stdio.h to do the output, what we need is an equivalent procedure to do the input. C has got one of these, it is called scanf (scan-formatted). However, before we can turn it loose we have a little problem to solve; Where does scanf put the value that it fetches. "That is easy" you say, simply give it the name of the variable and scanf will know where to go. Wrong! scanf is very stupid. It cannot understand the names of variables. Why should it? All it was created for is to take something from one place (the keyboard) and put it somewhere else (a location). scanf does not want to know what the variable is called, all it needs to know is where the variable lives. When we talk about C variables we mean a box which the compiler creates for us, with a name nicely painted on it. The compiler makes a box like this and then puts it on a shelf somewhere safe. The compiler then knows that when we say "i" we really mean the box with i written on it. scanf is simply a function that we call to fetch a value and stick it somewhere else, another kind of removal man. It needs to be told which box to put the result in. C calls referring to a thing by its location rather than its name as pointing. Nice children have been brought up knowing that it is rude to point. In C things are rather different, you have to point to be able to do anything useful. (I am sure nanny would understand). For more about pointers, see the chapter about Functions. When we want scanf to fetch something for us we have to give it a pointer. You can regard a pointer as a tag on the end of a piece of rope. The rope is tied to one of our boxes. All scanf has to do is follow the piece of rope to a box and then put the value into that box. You tell the C compiler to generate a pointer to a particular variable by putting an ampersand "&" in front of the variable name, i.e. x means the value of the variable x
  • 29. Writing a Program ? 24 &x means a pointer to the box where x is kept, i.e. the address of x. scanf looks very like printf, in that it is a format string followed by a list of items, but in this case the items pointers to variables, rather than values, for example: scanf ( "%d %d %d", &i, &j, &k) ; The more adventurous amongst you may be wondering what happens if we leave off the ampersands by mistake. This can lead to one of two things: 1. The compiler noticing that you have been a naughty programmer and taking you behind the bike sheds for a meaningful discussion. 2. scanf taking the value which it gets and stuffing it into a spurious chunk of memory, with the consequent and hilarious total failure of program and possibly computer. A very big chunk of C involves address and pointer juggling. I make no apologies for this, it is one of the things that makes C the wonderful, fun loving, language that it is. However it can also be a little hard on the grey matter. Just keep in mind that only the C compiler can handle sticking values into variables. Everything else does not know the name, and can only talk in terms of following pointers to boxes. Writing a Program Comments When the C compiler sees the "/*" sequence which means the start of a comment it says: Aha! Here is a piece of information for greater minds than mine to ponder. I will ignore everything following until I see a */ which closes the comment. Be generous with your comments. They help to make your program much easier to understand. You will be very surprised to find that you quickly forget how you got your program to work. You can also use comments to keep people informed of the particular version of the program, when it was last modified and why, and the name of the programmer who wrote it - if you dare! Program Flow The program above is very simple, it runs straight through from the first statement to the last, and then stops. Often you will come across situations where your program must change what it does according to the data which is given to it. Basically there are three types of program flow :
  • 30. Writing a Program ? 25 1. straight line 2. chosen depending on a given condition 3. repeated according to a given condition Every program ever written is composed of the three elements above, and very little else! You can use this to good effect when designing an overall view of how your program is going to work. At the moment we have only considered programs which run in a straight line and then stop. The path which a program follows is sometimes called its "thread of execution". When you call a function the thread of execution is transferred into the function until it is complete. Conditional Execution - if The program above is nice, in fact our customer will probably be quite pleased with it. However, it is not perfect. The problem is not with the program, but with the user. If you give the program a window width of -1 it goes ahead and works out a stupid result. Our program does not have any checking for invalid widths and heights. The user might have grounds for complaint if the program fails to recognise that he has given a stupid value, in fact a number of cases are currently being fought in the United States courts where a program has failed to recognise invalid data, produced garbage and caused a lot of damage. What we want to do is notice the really stupid replies and tell the user that he has done something dubious. In our program specification, which we give the customer, we have said something like: The program will reject window dimensions outside the following ranges: width less than 0.5 metres width greater than 5.0 metres height less than 0.75 metres height greater than 3.0 metres This means that we have done all we can; If the program gets 1 rather than 10 for the width then that is the users' problem, the important thing from our point of view is that the above specification stops us from being sued! In order to allow us to do this the program must notice naughty values and reject them. To do this we need can use the construction: if (condition) statement or block we do if the condition is true else statement or block we do if the condition is false The condition determines what happens in the program. So what do we mean by a condition? C is very simple minded about this, essentially it says that any condition which is non-zero is true, any condition which is zero is false. A condition is therefore really something which returns a number, for example: if (1) printf ( "hello mum" ) ; - is valid, although rather useless as the condition is always true, so "hello mum" is always printed (note that we left the else portion off - this is OK because it is optional).
  • 31. Writing a Program ? 26 Conditions and Relational Operators To make conditions work for us we need a set of additional relational operators which we can use to make choices. Relational operators work on operands, just like numeric ones. However any expression involving them can only produce two values, 0 or 1. Zero if the expression is not true, one if it is. Relational operators available are as follows: == equals. If the left hand side and the right hand side are equal the expression has the value 1. If they are not equal the value is 0. 4 == 5 - would return 0, i.e. false. Note that it is not meaningful to compare floating point values in this way. Because of the fact that they are held to limited precision you might find that conditions fail when they should not for example the following equation : x = 3.0 * ( 1.0 / 3.0) ; - may well result in x containing 0.99999999, which would mean that : (x == 1.0) If you want to compare floating point values subtract them and see if the difference is very small. - would be false - even though mathematically the test should return true. != not equal. The reverse of equal. If they are not equal the expression has the value 1, if they are equal it has the value 0. Again, this test is not suitable for use with floating point numbers. < less than. If the item on the left is less than the one on the right the value of the expression is 1. If the left hand value is larger than or equal to the right hand one the expression gives 0. It is quite valid to compare floating point numbers in this way. > greater than. If the expression on the left is greater than the one on the right the result is 1. If the expression on the left is less than or equal to the one on the right the result is 0. <= less than or equal to. If the expression on the left is less than or equal to the one on the right you get 1, otherwise you get 0. >= greater than or equal to. If the value on the left is greater than or equal to the one on the right you get 1, otherwise it is 0.
  • 32. Writing a Program ? 27 ! not. This can be used to invert a particular value or expression, for example you can say !1, which is 0, or you could say: !(x=y) - which means the same as (x!=y). You use not when you want to invert the sense of an expression. Combining Logical Operators Sometimes we want to combine logical expressions, to make more complicated choices, for example to test for a window width being valid we have to test that it is greater than the minimum and less than the maximum. C provides additional operators to combine logical values : && and. If the expressions each side of the && are true the result of the && is true. If one of them is false the result is false, for example (width > 0.5) && (width < 5.0) ) - this would be true if the width was valid according to our above description. || or. If either of the expressions each side of the || are true the result of the whole expression is true. The expression is only false if both expressions are false, for example : (width <= 0.5) | (width >= 5.0) ) De Morgans theorem is the basis of this. - this would be true if the width was invalid according to our above description. Note that if we put an or in we have to also flip the conditional operators around as well. Using these operators in conjunction with the if statement we can make decisions and change what our program will do in response to the data we get. Lumping Code Together We have decided that if the user gives a value outside our allowed range an error is generated and the value is then set to the appropriate maximum or minimum. To do this we have to do two statements which are selected on a particular condition, one to print out the message and the other to perform an assignment. You can do this by using the { and } characters. A number of statements lumped together between { and } characters is regarded as a single statement, so we do the following: if ( width > 5.0 ) { printf ( "Width too big, using maximum n" ) ; width = 5.0 ; } The two statements are now a block, which is performed only if width is greater than 5.0. You can lump many hundreds of statements together in this way, the compiler does not mind. You can also put such blocks of code inside other blocks, this is called nesting. The number of { and } characters must agree in your program, otherwise you will get strange and incomprehensible errors when the compiler hits the end of the file in the middle of a block or reaches the end of your program half way down your file!
  • 33. Writing a Program ? 28 I make things much easier to understand by indenting a particular block by a number of spaces, i.e. each time I open a block with the { character I move my left margin in a little way. I can then see at a glance whereabouts I am in the levels at any time. Magic Numbers and #define A magic number is a value with a special meaning. It will never be changed within the program, it is instead a constant which is used within it. When I write my glazing program I will include some magic numbers which give the maximum and minimum values for heights and widths. I could just use the values 0.5, 5.0, 0.75 and 3.0 - but these are not packed with meaning and make the program hard to change. If, for some reason, my maximum glass size becomes 4.5 metres I have to look all through the program and change only the appropriate values. I do not like the idea of "magic numbers" in programs, what I would like to do is replace each number with something a bit more meaningful. We can do this by using a part of the compiler called the C pre-processor. The pre-processor sits between your program and the compiler. It can act as a kind of filter, responding to directives in your program, and doing things to the text before the compiler sees it. We are just going to look at the one directive at the moment, #define: #define PI 3.141592654 Whenever the pre-processor sees PI it sends the compiler 3.141592654. This means that you can do things like: circ = rad * 2 * PI ; The item which follows the #define directive should be a sequence of characters. You then have a space, followed by another sequence of characters. Neither of the two sequences are allowed to contains spaces, this would get the pre-processor confused. Anywhere you use a magic number you should use a definition of this form, for example: #define MAX_WIDTH 5.0 This makes your programs much easier to read, and also much easier to change. There is a C convention that you always give the symbol you are defining in CAPITAL LETTERS. This is so that when you read your program you can tell which things have been defined. Note that the #define directive is not intelligent, and you can therefore stop your program from working by getting your definition wrong. Consider the effect of: #define MAX_WIDTH *this*will*cause*an*explosion! There are loads more pre-processor directives which you can use, the other one which we have already seen is #include. We can therefore modify our double glazing program as follows: /* Double Glazing 2 */ /* This program calculates glass area and wood */ /* required by a double glazing salesman. */ /* Version 22.15 revision level 1.23 */ /* Rob Miles - University of Hull - 13/11/89 */ #include <stdio.h>
  • 34. Writing a Program ? 29 #define MAX_WIDTH 5.0 #define MIN_WIDTH 0.5 #define MAX_HEIGHT 3.0 #define MIN_HEIGHT 0.75 void main () { float width, height, glassarea, woodlength ; printf ( "Give the width of the window : " ) ; scanf ( "%f", &width ) ; if (width < MIN_WIDTH) { printf ( "Width is too small. nn" ) ; width = MIN_WIDTH ; } if (width > MAX_WIDTH) { printf ( "Width is too large. nn" ) ; width = MAX_WIDTH ; } scanf ( "%f", &height ) ; if (height < MIN_HEIGHT) { printf ( "Height is too small. nn" ) ; height = MIN_HEIGHT ; } if (height > MAX_HEIGHT) { printf ( "Height is too large. nn" ) ; height = MAX_HEIGHT ; } woodlength = 2 * (width + height) ; glassarea = width * height ; printf ( "Glass : %f Wood : %f nn", woodlength, glassarea ) ; } This program fulfills our requirements. It will not use values incompatible with our specification. However I would still not call it perfect. If our salesman gives a bad height the program stops and needs to be re-run, with the height having to be entered again. What we would really like is a way that we can repeatedly fetch values for the width and height until we get one which fits. C allows us to do this by providing a looping constructions. Loops Conditional statements allow you to do something if a given condition is true. However often you want to repeat something while a particular condition is true, or a given number of times. C has three ways of doing this, depending on precisely what you are trying to do. Note that we get three methods not because we need three but because they make life easier when you write the program (a bit like an attachment to our chainsaw to allow it to perform a particular task more easily). Most of the skill of programming involves picking the right tool or attachment to do the job in hand. (the rest is finding out why the tool didn't do what you expected it to!). In the case of our program we want to repeatedly get numbers in until while we are getting duff ones, i.e. giving a proper number should cause our loop to stop.
  • 35. Writing a Program ? 30 This means that if we get the number correctly first time the loop will execute just once. You might think that I have pulled a fast one here, all I have done is change: Get values until you see one which is OK into Get values while they are not OK Part of the art of programming is changing the way that you think about the problem to suit the way that the programming language can be told to solve it. Further details can be found in Zen and the Art of 68000 Assembler from Psychic Press at £150. do -- while loop In the case of our little C program we use the do -- while construction which looks like this: do statement or block while (condition) ; This allows us to repeat a chunk of code until the condition at the end is true. Note that the test is performed after the statement or block, i.e. even if the test is bound to fail the statement is performed once. A condition in this context is exactly the same as the condition in an if statement, raising the intriguing possibility of programs like: #include <stdio.h> void main () { do printf ( "hello mum n" ) ; while (1) ; } This is a perfectly legal C program. How long it will run for is an interesting question, the answer contains elements of human psychology, energy futures and cosmology, i.e. it will run until: 1. You get bored with it. 2. Your electricity runs out. 3. The universe implodes. This is a chainsaw situation, not a powerful chainsaw situation. Just as it is possible with any old chainsaw to cut off your leg if you try really hard so it is possible to use any programming language to write a program which will never stop. It reminds me of my favourite shampoo instructions: 1. Wet Your Hair 2. Add Shampoo and Rub vigorously. 3. Rinse with warm water. 4. Repeat. I wonder how many people there are out there still washing their hair at the moment.
  • 36. Writing a Program ? 31 while loop Sometimes you want to decide whether or not to repeat the loop before you perform it. If you think about how the loop above works the test is done after the code to be repeated has been performed once. For our program this is exactly what we want, we need to ask for a value before we can decide whether or not it is valid. In order to be as flexible as possible C gives us another form of the loop construction which allows us to do the test first: while (condition) statement or block Note that C makes an attempt to reduce the number of keys you need to press to run the program by leaving out the word do. (if you put the do in the compiler will take great delight in giving you an error message - but you had already guessed that of course!). for loop Often you will want to repeat something a given number of times. The loop constructions we have given can be used to do this quite easily: #include <stdio.h> void main () { int i ; i = 1 ; while ( i < 11) { printf ( "hellon" ) ; i = i + 1 ; } } The variable which controls things is often called the control variable, and is usually given the name i. This useless program prints out hello 10 times. It does this by using a variable to control the loop. The variable is given an initial value (1) and then tested each time we go around the loop. The control variable is then increased for each pass through the statements. Eventually it will reach 11, at which point the loop terminates and our program stops. C provides a construction to allow you to set up a loop of this form all in one: for ( setup ; finish test ; update ) { things we want to do a given number of times } We could use this to re-write the above program as: #include <stdio.h> void main () { int i ; for ( i=0 ; i != 11 ; i = i+1 ) { printf ( "hellon" ) ; } } The setup puts a value into the control variable which it will start with. The test is a condition which must be true for the for -- loop to continue. The update is the statement which is performed to update the control variable at the end of each loop. Note that the three elements are separated by semicolons. The precise sequence of events is as follows:
  • 37. Writing a Program ? 32 1. Put the setup value into the control variable. 2. Test to see if we have finished the loop yet and exit to the statement after the for loop if we have. 3. Perform the statements to be repeated. 4. Perform the update. 5. Repeat from step 2. Writing a loop in this way is quicker and simpler than using a form of while because it keeps all the elements of the loop in one place, instead of leaving them spread about the program. This means that you are less likely forget to do something like give the control variable an initial value, or update it. If you are so stupid as to mess around with the value of the control variable in the loop you can expect your program to do stupid things, i.e. if you put i back to 0 within the loop it will run forever..... Breaking Out of Loops Sometimes you may want to escape from a loop whilst you are in the middle of it, i.e. your program may decide that there is no need or point to go on and wishes to tunnel out of the loop and continue the program from the statement after it. You can do this with the break statement. This is a command to leap out of the loop immediately. Your program would usually make some form of decision to quit in this way. I find it most useful so that I can provide a get the hell out of here option in the middle of something, for example in the following program snippet the variable aborted, normally 0 becomes 1 when the loop has to be abandoned and the variable runningOK, normally 1, becomes 0 when it is time to finish normally. while (runningOK) { complex stuff .... if (aborted) { break ; } .... more complex stuff .... } .... bit we get to if aborted becomes true .... Note that we are using two variables as switches, they do not hold values as such, they are actually used to represent states within the program as it runs. This is a standard programming trick that you will find very useful. You can break out of any of the three kinds of loop. In every case the program continues running at the statement after the last statement of the loop. Going Back to the Top of a Loop Every now and then you will want to go back to the top of a loop and do it all again. This happens when you have gone as far down the statements as you need to. C provides the continue statement which says something along the lines of:
  • 38. Writing a Program ? 33 Please do not go any further down this time round the loop. Go back to the top of the loop, do all the updating and stuff and go around if you are supposed to. In the following program the variable Done_All_We_Need_This_Time is set when we have gone as far down the loop as we need to. for ( item = 1 ; item < Total_Items ; item=item+1 ) { ..... item processing stuff .... if (Done_All_We_Need_This_Time) { continue ; .... additional item processing stuff .... } The continue causes the program to re-run the loop with the next value of item if it is OK to do so. You can regard it as a move to step 2 in the list above. More Complicated Decisions We can now think about using a loop to test for a valid width or height. Essentially we want to keep asking the user for a value until we get one which is OK; i.e. if you get a value which is larger than the maximum or smaller than the minimum ask for another. To do this we have to combine two tests to see if the value is OK. Our loop should continue to run if: width > MAX_WIDTH or width < MIN_WIDTH To perform this test we use one of the logical operators described above to write a condition which will be true if the width is invalid: ( (width < MIN_WIDTH) || (width > MAX_WIDTH) ) - note the profuse use of brackets. You must put these in. Complete Glazing Program This is a complete solution to the glazing problem. It uses all the tricks mentioned above, plus a few which are covered below. /* Complete Double Glazing Program */ /* Rob Miles Nov. 1990 */ #include <stdio.h> /* Define our window size range */ #define MAX_HEIGHT 3.0 #define MAX_WIDTH 5.0 #define MIN_HEIGHT 0.75 #define MIN_WIDTH 0.5 /* Define a few costs */ #define COST_TO_MAKE 2.00 #define WOOD_COST 2.00