




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
author professor course subjet
Typology: Schemes and Mind Maps
1 / 217
This page cannot be seen from the preview
Don't miss anything!





























































































i
All rights reserved. No large-scale reproduction, copy or transmission of this publication may be made without written permission. Individual copies can be printed for personal use. The author can be contacted at: Email: [email protected] Blog: www.robmiles.com Twitter @RobMiles If you find a mistake in the text, please report the error to [email protected] and I will take a look. Thanks to Liz, Dina, Lilli, Neil, Richard, William, Don, Bram, Mitch, Jaswinder, Javi, Peter, Justin, James, Mike, Ian, Papartis, Hassan, Drew and Johan who have all done just that and made the book even better.
iii The cheese was delicious.
Computers and Programs Computers 1 Computers and Programs In this chapter you are going to find out what a computer is and get an understanding of the way that a computer program tells the computer what to do. You will discover what you should do when starting to write a program, to ensure that you achieve a “happy ending” for you and your customer. Finally, you will take a look at programming in general and the C# language in particular. 1.1 Computers Before we consider programming, we are going to consider computers. This is an important thing to do, because it sets the context in which all the issues of programming itself are placed.
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 hums. This, while 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 people do not write programs. They use 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:
If you ever buy a computer, you are not just getting a box which hums. 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 that the salesman sold you. 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, to do something useful. It is called software because it has no physical existence and it
Computers and Programs Computers is comparatively easy to change. Software is the voice which says "Computer Running" in a Star Trek film. Windows 10 is an example of an operating system. It gives computer programs a platform on which they can execute. 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.
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. As an example, the computer could hold the following bit pattern in memory somewhere: 11111111 11111111 11111111 00000000 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? (pedantic means being fussy about something being exactly right) Because it is vital to remember that a computer does not "know" what the data it is processing actually means. As far as the computer is concerned data is just patterns of bits, it is the user who gives meaning to these patterns. Remember this when you get a bank statement which says that you have £8,388,608 in your account!
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:
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 invalid data into a computer and it will do equally useless things. It is only us people who actually give meaning to the data (see above). As far as the computer is concerned data is just stuff coming in which has to be manipulated in some way. 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.
Computers and Programs Programs and Programming 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:
And remember just how much plumbers earn…. 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 is not about mathematics, it is about organization and structure. 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 a 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. Many software projects have failed because the problem that they solved was the wrong one. The developers of the system quite simply did not find out what was required, but instead created what they thought was required. The customers assumed that, since the developers had stopped asking them questions, the right thing was being built, and only at the final handover was the awful truth revealed. It is therefore very important that a programmer holds off making something until they know exactly what is required. 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 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 is 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 such a definition is sometimes called a Functional Design Specification or FDS. This tells you exactly what the customer wants. Both you and the
Computers and Programs Programs and Programming 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 some form of specification forces you to think about your problem at a very detailed level. It also forces you to think about what your system is not going to do and sets the expectations of the customer right at the start.
I have written many programs for money. I would never write a program without getting a solid specification first. This is true even (or perhaps especially) if I do a job for a friend. Modern development techniques put the customer right at the heart of the development and involve them in the design process. These work on the basis that it is very hard (and actually not that useful) to get a definitive specification at the start of a project. You as a developer don’t really know much about the customer’s business and they don’t know the limitations and possibilities of the technology. With this in mind it is a good idea to make a series of versions of the solution and discuss each with the customer before moving on to the next one. This is called prototyping.
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 printout 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 to a price you start work. The first thing you need to do is find out exactly what the customer wants you to do...
When considering how to write the specification of a system there are three important things:
In the case of our immortal double-glazing problem we can describe the information as:
The information that our customer wants to see is:
Computers and Programs Programs and Programming
In a real world you would now create a test 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 tell me I need 4 square metres of glass and 19.5 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. 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. Testing is a very important part of program development. There is even one development technique where you write the tests before you write the actual program that does the job. This is actually a good idea, and one we will explore later. In terms of code production, you can expect to write as much code to test your solution as is in the solution itself. Remember this when you are working out how much work is involved in a particular job.
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 will have no option but to pay 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! The good news for the developer is that if changes are requested these can be viewed in the context of additional work, for which they can expect to be paid.
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. Quite often prototypes will be used to get an idea of how the program should look and feel. 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, Rob's law says that 60% of the wrong 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 posh 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. They will get a bit upset when the delivery deadline goes by without a finished product appearing but they can always cheer themselves up again by suing you. Actually, we have come full circle here, because I did mention earlier that prototyping is a good way to build a system when you are not clear on the initial specification. However, if you are going to use prototypes it is a good thing to plan for this from the
Computers and Programs Programming Languages start rather than ending up doing extra work because your initial understanding of the problem was wrong. Fact: More implementations fail because of inadequate specification than for any other reason! If your insistence 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 times 2 and print it calculate ( width + height ) * 2 * 3.25 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.......
The art of talking to a customer and finding out what he/she wants is just that, an art. If you want to call yourself a proper programmer you will have to learn how to do this. One of the first things you must do is break down the idea of "I am writing a program for you" and replace it with "We are creating a solution to a problem". You do not work for your customers, you work with them. This is very important, particularly when you might have to do things like trade with the customer on features or price. 1.3 Programming Languages Once we know what the program should do (specification), and how we are going to determine whether it has worked or not (test) we now need to express our program in a form that the computer can work with. 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:
Computers and Programs C# with it. Switching to unmanaged mode is analogous to removing the guard from your new chainsaw because it gets in the way. C# is a great language to start learning with as the managed parts will make it easier for you to understand what has happened when your programs go wrong.
The C# language is object oriented. Objects are an organisational mechanism which let you break your program down into sensible chunks, each of which is in charge of part of the overall system. Object Oriented Design makes large projects much easier to design, test and extend. It also lets you create programs which can have a high degree of reliability and stability. I am very keen on object oriented programming, but I am not going to tell you much about it just yet. This is not because I don't know much about it (honest) but because I believe that there are some very fundamental programming issues which need to be addressed before we make use of objects in our programs. The use of objects is as much about design as programming, and we have to know how to program before we can design larger systems.
You actually write the program using some form of text editor - which may be part of the compiling and running system. C# is a compiled programming language. The computer cannot understand the language directly, so a program called a compiler converts the C# text into the low level instructions which are much simpler. These low level instructions are in turn converted into the actual commands to drive the hardware which runs your program. We will look in more detail at this aspect of how C# programs work a little later, for now the thing to remember is that you need to show your wonderful C# program to the compiler before you get to actually run it. A compiler is a very large program which knows how to decide if your program is legal. The first thing it does is check for errors in the way that you have used the language itself. Only if no errors are found by the compiler will it produce any output. The compiler will also flag up warnings which occur when it notices that you have done something which is not technically illegal, but may indicate that you have made a mistake somewhere. An example of a warning situation is where you create something but don't use it for anything. The compiler would tell you about this, in case you had forgotten to add a bit of your program. The C# language is supplied with a whole bunch of other stuff (to use a technical term) which lets C# programs do things like read text from the keyboard, print on the screen, set up network connections and the like. These extra features are available to your C# program but you must explicitly ask for them. They are then located automatically when your program runs. Later on we will look at how you can break a program of your own down into a number of different chunks (perhaps so several different programmers can work on it).
Microsoft has made a tool called Visual Studio, which is a great place to write programs. It comprises the compiler, along with an integrated editor, and debugger. It is provided in a number of versions with different feature sets. There is a free version, called Visual Studio Express edition, which is a great place to get started. Another free resource is the Microsoft .NET Framework. This provides a bunch of command line tools, i.e. things that you type to the command prompt, which can be used to compile and run C# programs. How you create and run your programs is up to you.
Computers and Programs C# I'm not going to go into details of how to download and install the .NET framework; that is for other documents, I am going to assume that you are using a computer which has a text editor (usually Notepad) and the .NET framework installed.
Of 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!
If your mum wanted to tell you how to make your favourite fruitcake she’d write the recipe down on a piece of paper. The recipe would be a list of ingredients followed by a sequence of actions to perform on them. A program can be regarded as a recipe, but written for a computer to follow, not a cook. The ingredients will be values (called variables ) that you want your program to work with. The program itself will be a sequence of actions (called statements ) that are to be followed by the computer. Rather than writing the program down on a piece of paper you instead put it into a file on the computer, often called a source file. This is what the compiler acts on. A source file contains three things:
. The C# compiler needs to know certain things about your program. It needs to know which external resources your program is going to use. It also can be told about any options for the construction of your program which are important. Some parts of your program will simply provide this information to tell the compiler what to do.
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. As part of the program design process you will need to decide what items of data need to be stored. You must also decide on sensible names that you will use to identify these items.
Simple Data Processing A First C# Program 2 Simple Data Processing In this chapter we are going to create a genuinely useful program (particularly if you are in the double glazing business). We will start by creating a very simple solution and investigating the C# statements that perform basic data processing. Then we will use additional features of the C# language to improve the quality of the solution we are producing. 2.1 A First C# Program The first program that we are going to look at will read in the width and height of a window and then print out the amount of wood and glass required to make a window that will fit in a hole of that size. This is the problem we set out to solve as described in section1.2.
Perhaps the best way to start looking at C# is to jump straight in with our first ever C# program. Here it is: Code Sample 0 1 GlazerCalc Program This is a valid program. If you gave it to a C# compiler it would compile, and you could run it. The actual work is done by the two lines that I have highlighted. Broadly speaking the stuff before these two lines is concerned with setting things up and getting the values in to be processed. The stuff after the two lines is concerned with displaying the answer to the user. We can now go through each line in turn and try to see how it fits into our program. using System; class GlazerCalc { static void Main() { double width, height, woodLength, glassArea; string widthString, heightString; widthString = Console.ReadLine(); width = double.Parse(widthString); heightString = Console.ReadLine(); height = double.Parse(heightString); woodLength = 2 * ( width + height ) * 3.25 ; glassArea = 2 * ( width * height ) ; Console.WriteLine ( "The length of the wood is " + woodLength + " feet" ) ; Console.WriteLine( "The area of the glass is " + glassArea + " square metres" ) ; } }
Simple Data Processing A First C# Program
A big part of learning to program is learning how to use all the additional features of the system which support your programs. This is an instruction to the C# compiler to tell it that we want to use things from the System namespace. A namespace is a place where particular names have meaning. We have namespaces in our conversations too, if I am using the "Football" namespace and I say “That team is really on fire” I'm saying something good. If I am using the "Firefighter" namespace I'm saying something less good. In the case of C# the System namespace is where lots of useful things are described. One of these useful things provided with C# is the Console class which will let me write things which will appear on the screen in front of the user. If I want to just refer to this as Console I have to tell the compiler I'm using the System namespace. This means that if I refer to something by a particular name the compiler will look in System to see if there is anything matching that name. We will use other namespaces later on.
Classes are the basis of object oriented programming, as we shall see later. A C# program is made up of one or more classes. A class is a container which holds data and program code to do a particular job. In the case of our double glazing calculator the class just contains a single method which will work out our wood lengths and glass area, but a class can contain much more than that if it needs to. You need to invent an identifier for every class that you create. I've called ours GlazerCalc since this reflects what it does. For now, don't worry too much about classes; just make sure that you pick sensible names for the classes that you create. Oh, and one other thing. There is a convention that the name of the file which contains a particular class should match the class itself, in other words the program above should be held in a file called GlazerCalc.cs.
This keyword makes sure that the method which follows is always present, i.e. the word static in this context means "is part of the enclosing class and is always here". When we get to consider objects we will find that this little keyword has all kinds of interesting ramifications. But for now I'd be grateful if you'd just make sure that you put it here in order to make your programs work properly.
A void is nothing. In programming terms the void keyword means that the method we are about to describe does not return anything of interest to us. The method will just do a job and then finish. In some cases we write methods which return a result (in fact we will use such a method later in the program). However, in order to stop someone else accidentally making use of the value returned by our Main method, we are explicitly stating that it returns nothing. This makes our programs safer, in that the compiler now knows that if someone tries to use the value returned by this method, this must be a mistake.
You choose the names of your methods to reflect what they are going to do for you. Except for Main. This method (and there must be one, and only one such method) is where your program starts running. When your program is loaded and run the first method given control is the one called Main. If you miss out the Main method the system quite literally does not know where to start.