Sunteți pe pagina 1din 33

Introduction to Flowcharting

The flowchart is a means of visually presenting the flow of data through an information processing system, the operations performed within the system and the sequence in which they are performed. The program flowchart describes what operations (and in what sequence) are required to solve a given problem. The program flowchart can be likened to the blueprint of a building. As we know, a designer draws a blueprint before starting construction on a building. Similarly, a programmer prefers to draw a flowchart prior to writing a computer program. As in the case of the drawing of a blueprint, the flowchart is drawn according to defined rules and using standard flowchart symbols prescribed by the American National Standard Institute, Inc. OBJECTIVES At the end of this chapter, you will be able to understand:

the meaning of flowchart the basic parts of the flowchart such as flowchart symbols and the flow lines connecting these symbols. the advantages and limitations of flowchart

MEANING OF A FLOWCHART A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Therefore, it is correct to say that a flowchart is a must for the better documentation of a complex program. GUIDELINES FOR DRAWING A FLOWCHART Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently required for flowcharting are given below. Symbols are used to represent functions. These fundamental functions are processing, decision, input/output, terminal, flow lines, and connector symbol. All flowcharts may be initially constructed using only these fundamental symbols as a rough outline to work from. Each symbol corresponds to one of the functions of a computer and specifies the instruction(s) to be performed by the computer. The contents of these symbols are called

statements. Samples of these fundamental symbols, definitions, examples, and explanations of their uses are :

GRAPHIC SYMBOLS. - Within a flowchart, graphic symbols are used to specify arithmetic operations and relational conditions. The following are commonly-used arithmetic and relational symbols. + plus, add - minus, subtract * multiply / divide plus or minus

= equal to > greater than < less than

greater than or equal to less than or equal to

not equal YES or YYes NO or NNo TRUE or TTrue FALSE or FFalse FLOWCHARTING TEMPLATE. - To aid in drawing the flowcharting symbols, you may use a flowcharting template. Figure 3-4 shows a template containing the standard symbol cutouts. A template is usually made of plastic with the symbols cut out to allow tracing the outline.

FLOWCHART WORKSHEET. - The flowchart worksheet is a means of standardizing documentation. It provides space for drawing programming flowcharts and contains an area for identification of the job, including application, procedure, date, and page numbers. You may find it helpful when you develop flowcharts. If you don't have this form available, a plain piece of paper will do.

Constructing a Flowchart There is no "best way" to construct a flowchart. There is no way to standardize problem solution. Flowcharting and programming techniques are often unique and conform to the individual's own methods or direction of problem solution. This section will show an example of developing a programming flowchart. It is not the intent to say this is the best way; rather, it is one way to do it. By following this text example you should grasp the idea of solving problems through flowchart construction. As you gain experience and familiarity with a computer system, these ideas will serve as a foundation. To develop a flowchart, you must first know what problem you are to solve. It is then your job to study the problem definition and develop a flowchart to show the logic, steps, and sequence of steps the computer is to execute to solve the problem. As an example, suppose you have taken a short-term second mortgage on a new home, and you want to determine what your real costs will be, the amount of interest, the amount to be applied to principal, and the final payment at the end of the 3-year loan period.

The first step is to be sure you understand the problem completely - What are the inputs and the outputs and what steps are needed to answer the questions? Even when you are specifying a problem of your own, you will find we don't usually think in small, detailed sequential steps. However, that is exactly how a computer operates, one step after another in a specified order. Therefore, it is necessary for you to think the problem solution through step by step. You might clarify the problem as shown by the Problem Definition in the following figure.

After you have this level of narrative problem definition, you are ready to develop a flowchart showing the logic, steps, and sequence of steps you want the computer to execute to solve the problem. A programming flowchart of this problem is also shown in figure. Study both the problem definition and the flowchart to see their relationship and content. You now have a plan of what you want the computer to do. The next step is to code a program that can be translated by a computer into a set of instructions it can execute. This step is called program coding. The following are some guidelines in flowcharting: a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order. b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart. c. The usual direction of the flow of a procedure or system is from left to right or top to bottom. d. Only one flow line should come out from a process symbol. or e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, should leave the decision symbol. f. Only one flow line is used in conjunction with terminal symbol. g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly. h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication. i. Ensure that the flowchart has a logical start and finish. j. It is useful to test the validity of the flowchart by passing through it with a simple test data. ADVANTAGES OF USING FLOWCHARTS The benefits of flowcharts are as follows: 1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned. 2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.

3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes. 4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase. 5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part LIMITATIONS OF USING FLOWCHARTS 1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy. 2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely. 3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. 4. The essentials of what is done can easily be lost in the technical details of how it is done. IN-TEXT QUESTIONS 1 1. Fill in the blank. i. ii. iii. iv. v. vi. vii. viii. ix. x. A program flowchart indicates the_________ to be performed and the __________ in which they occur. A program flowchart is generally read from _____________ to ________________ Flowcharting symbols are connected together by means of ___________________ A decision symbol may be used in determining the ____________ or ___________ of two data items. __________ are used to join remote portions of a flowchart. ____________ connectors are used when a flowchart ends on one page and begins again on other page A ________ symbol in used at the beginning and end of a flowchart. The flowchart is one of the best ways of ________ a program.. To construct a flowchart, one must adhere to prescribed symbols provided by the __________ . The programmer uses a ____________ to aid him in drawing flowchart symbols.

What is programming?
Given the general nature of that question, and the fact that programming is seen as a hideously complex subject, you're probably expecting a highly convoluted and technical answer. But you're not going to get one (sorry about that). In truth, it's quite easy to say what programming is, so I will:

Programming is breaking a task down into small steps.

That's just about the most honest and accurate answer I can give. It also has the added benefit of being concise, and sounding very much like something you'd read in an official book on the topic, thus adding to my credibility. You're perhaps wondering what exactly I mean by breaking a task down into small steps, so I'll explain the point in more detail. Let me start by giving you a fact about programmers that you'll find very easy to believe:

Programmers think in an unnatural way.

This refers just to the fact that programming is breaking a task into small steps, and that's not the usual way that your mind works. An example will help you to understand what I mean. Here's a task for you to do: Put these words in alphabetical order: apple, zebra, abacus I'm going to assume that you managed to put them in alphabetical order, and ended up with abacus, then apple, then zebra. If you didn't manage that, reading further may soon become one of the worst experiences of your life so far. Now think about exactly how you performed that task; what steps you took to put the words in alphabetical order, and what you required to know in order to do so. The most obvious thing you needed to know was the alphabet; the desired order of the letters. Then, if you're like me, you probably did something like this: 1. Look through the words for one beginning with "A". 2. If you found a word beginning with "A", put that word at the beginning of the list (in your mind). 3. Look for another word beginning with "A". 4. If there's another word beginning with "A", compare its second letter with the second letter of our first "A" word. 5. If the second letters are different, put the two words in alphabetical order by their second letter. If the second letters are the same, proceed to the third letter, and so on. 6. Repeat this whole process for "B" and each other letter in alphabetical order, until all the words have been moved to the appropriate place.

Your method may differ slightly, but probably not by much. The thing to notice (which I noticed particularly, since I'm having to type all this) is how much time it took to explain a process which happens without any real conscious thought. When you saw that you had to put some words in alphabetical order, you certainly didn't first sit down and draw up a plan of what you were going to do, detailing all the steps I listed above. Your mind doesn't need to; you learned to do it once when you were a child, and now it just happens. You have a kind of built-in shortcut to that sequence of steps. Now let's try another simple example: Count the number of words in this sentence: "Programming really can be fun." Hopefully you decided that there were five words. But how did you come to that decision? First you had to decide what a word is, naturally. Let's assume for the moment that a word is a sequence of letters which is separated from other words by a space. Using that rule, you do indeed get five words when looking at the sentence above. But what about this sentence: "Sir Cecil Hetherington-Smythe would make an excellent treasurer,minister." Notice my deliberate mistake: I didn't leave a space after the comma. You might also feel it's a mistake to name anyone Cecil Hetherington-Smythe, but that's a debate for another time. Using our rule about sequences of letters which are separated from other sequences by spaces, you would decide that there were eight words in the new sentence. However, I think we can agree that there are in fact ten words, so our rule clearly isn't working. Perhaps if we revised our rule to say that words can be separated by spaces, commas or dashes, instead of just spaces. Using that new rule, you'd indeed find ten words. Now let's try another sentence: "Some people just love to type really short lines, instead of using the full width of the page." Although it might not be obvious, there is no space after "really", nor is there a space after "full". Instead, I took a new line by pressing the return key. So, using our newest rule, how many words would you find in that last sentence? I'll tell you: you'd get sixteen, when in fact there are eighteen. This means that we need to revise our rule yet again, to include returns as valid word-separators. And so on, until another sentence trips up our rule, and we need to revise it yet again. You might wonder why we're doing this at all, because after all, we all know what we mean when we say "count the number of words". You can do it properly without thinking about any rules or valid word-separators or any such thing. So can I. So can just about anyone. What this example has shown us is that we take for granted something which is actually a pretty sophisticated "program" in our minds. In fact, our own built-in word

counting "program" is so sophisticated that you'd probably have a lot of trouble describing all the actual little rules it uses. So why bother? The answer comes in the form of an exceptionally important truth which you must learn. It is to do with computers. Here it is:

Computers are very, very stupid.

To some people, that statement is almost sacrilegious. You can understand that, because computers are really expensive. If you've just bought a Ferrari, you probably don't want your neighbour to come along and say that it is ugly and slow. If you're a Mac user, you might actually kill a person who said your computer was stupid. Nevertheless, it's true - computers are desperately stupid. Your computer will sit there and do whatever mindless task you tell it to, for days, weeks, months or years on end, without any complaints or any slacking-off. That is not the typical behaviour of something that is even slightly clever. It will also happily erase it's own hard disk (which is a bit like you deleting all your memories then pulling parts of your brain out), so we are clearly not dealing with an intimidating intelligent item. In fact, computers are so painfully stupid that they require to be told, in minute detail, how to do even the most laughably simple of tasks. It's quite pathetic, when you think about it (or perhaps we're pathetic, since we're willing to pay ridiculous amounts of money to own them). In fact, just about the only positive thing about computers is that they're completely obedient. No matter how crazy your instructions might be, your computer will carry them out precisely. By now, hopefully you can see how this is all tying together. Programmers tell computers what to do. Computers require these instructions to be precise and complete in every way. Humans aren't usually good at giving precise and complete instructions since we have this incredible brain which lets us give vague commands and still get the correct answer. Thus, programmers have to learn to think in an unnatural way: they have to learn to take a description of a task (like "count the number of words in a sentence"), and break it down into the fundamental steps which a computer needs to know in order to perform that task. You may be feeling slightly uneasy at this point. I've admitted that programming is, in a way, unnatural. I've warned you about the spectacular stupidity of computers, so you're probably getting a small idea of the amount of task-description you'd need to do in order to make your computer do anything even vaguely impressive. But don't worry; there are some excellent reasons to become a programmer:

Programmers make lots of money. Programming really is fun. Programming is very intellectually rewarding. Programming makes you feel superior to other people.

Programming gives you complete control over an innocent, vulnerable machine, which will do your evil bidding with a loyalty not even your pet dog can rival.

At least some if not all of these points will instantly appeal to you as a human being, and it's none of my business which ones you find most attractive. Additionally, people have been programming for many years, and so have already written many task-descriptions ("programs") for a lot of common tasks, so you can use all their hard work to save yourself some trouble, which is also a very attractive prospect, I'm sure. If you're still not sure whether programming is for you, perhaps the next section will help you decide.

An Introduction to Programming
Welcome! This section is the first step on your adventure into the fascinating world of computer programming. We don't assume that you know anything about programming at the moment, but we hope that by the time you've finished this section you'll have enough confidence and knowledge to go on to explore the rest of this fascinating world all by yourself. As a result, this section is going to concentrate on the key concepts and skills that you'll need to master to become a programmer, rather than showing you all of the features of a specific programming language. So straight afterwards, you shouldn't expect to be able to create your own version of Doom or Word, but given a bit of time and practice - who knows! So, lets start at the beginning... Loosely speaking, programming can be defined as: teaching a computer how to do something. Unfortunately, computers are phenomenally stupid as we discussed earlier : you can't just say to a computer 'create me a word processing package,' because it just won't understand. Computers have only a tiny set of skills and knowledge, and to get them to do anything you have to describe exactly what you want done in terms of that tiny set. This description is called a program, and consists of a list of every tiny step that the computer has to take to complete its task. A program is a bit like a very detailed set of directions of how to get from a to b: any mistake or omission in those directions can mean that the computer follows the wrong path and ends up at the wrong place; for very complex tasks these instructions can also become very long! However, even though computers are stupid - they're not useless. In fact, they're incredibly powerful, and once properly taught how to do something with a program, they can usually do it far faster and more reliably than any human.

Luckily, over the years, much of the basic education has been done. The early computing pioneers have already taught computers basic maths and a,b,c's, and in the process have developed many techniques to help us to educate computers/write programs more efficiently.

Why Should I Learn to Program?

Three reasons: 1. It's great fun - humans love problem solving (riddles, puzzles, whodunnits, Tomb Raider, etc.) and programming provides regular opportunities to do this. 2. It's very rewarding - watching a program that you've created running gives you one heck of a buzz. 3. And finally, for the less idealistic amongst you, it can be pretty lucrative!

The Programming Process

All programming involves creating something that solves a problem. The problems can range from something of great scientific or national importance, through to something as trivial as relieving personal boredom! This section describes one approach to solving such problems - think of it as a rough guide to the things you should do when entering the world of programming. In broad terms, those things are: 1. 2. 3. 4. Identify the Problem Design a Solution Write the Program Check the Solution

Of these, only the third step is usually called "programming", but as you'll see later, it's probably the least important stage of the process.

Identify the Problem

In fact, this stage should really be called identifying the solution because what you're really trying to do is to tie down exactly what it is that you're trying achieve. There are two stages to identifying a solution:

Requirements Specification


The first step is to examine the problem carefully to try to identify what qualifies as a solution. A single problem may have many different solutions, but they will all have something in common. So here you're trying to work out exactly what your program will be required to do. For example, if we were asked to write a calculator program, we could choose many different ways for the user to enter calculations - from entering equations, pressing buttons or even writing them on the screen - but if the software can't add up correctly then it won't have solved the problem. Therefore our first few requirements must be that:

the user can enter sums (we don't care how they do this) and that the program will then evaluate those and display the result for the user.



We also have to decide what sort of sums our calculator will be required to evaluate. Again, we have a fair amount of choice - we could be ambitious and ask it to solve simultaneous equations or complex expressions, however since this is our first program we should probably make the requirements more simple. So the third requirement is that:

The calculator must be able to evaluate sums made up of two whole numbers (integer operands) and one addition (+), subtraction (-), multiplication (*) or division (/) sign (operator).

Note that computer scientists traditionally use * instead of x and / instead of to indicate multiplication and division respectively. Thus our calculator must be able to deal with sums like 1 + 1, 10 - 6, 43 * 5 and 42 / 7. However it won't have to handle 67.345 + 6, the cube root of PI or 15 .

Specification The second step is to then look at the list of requirements and to decide exactly what your solution should do to fulfill them. As we mentioned above, there are usually many different solutions to a single problem; here, your aim is to decide on which of those solutions you want. Therefore, you're trying to specify, in a fairly accurate manner, just what it is your final program will do.

For example, for the calculator, we've already decided that the program must allow us to enter simple sums and then must evaluate them correctly and display an answer. We must now tie down exactly what this means. Therefore, we have to decide which method of entering sums to use. We could specify any one of a number of methods, but for now, we'll choose a simple method. We should also specify what other behaviour we're expecting the program to have:

When the program runs it will display a welcome message, followed by some simple instructions. The program will then display a prompt sign ( [number]>) and the user can then type the first number of their sum at the keyboard followed by the RETURN ( ') key. The program will display a second prompt sign ( [+-/*]>) and the user can then enter the operator that they wish to use, followed by RETURN. A third prompt sign will be displayed ( [number]>) and the user will then enter the second number, again followed by RETURN. The calculator program will then display the mathematically correct answer to the sum on the screen and end.

By the time you have worked out your specification, you should have a very clear idea of what your final program will do: your goal.

Design a Solution
Once you've identified the things required to solve your problem, and specified what form your solution will take, the next step is to work out just how you're going to turn that specification into a working program. This is usually the hardest task! As mentioned before, a program is simply a list of steps describing to the computer what it should do. A design is simply a higher-level description of those steps. In effect it's a program written as if the computer was a person. So, it doesn't have to completely spell out every step - because humans know how to do a lot of things already and have a lot of common sense, meaning that they can work the simple steps out for themselves. It also doesn't have to be written in any special programming language - English will do (although people often use special notations like pseudo code or flow charts for the more complicated sections). Another way of looking at is that a programmer should be able to take a design and write the program from it without having to think too hard. It's a bit like an architect's drawing: it contains all the important structures without showing every bit of brick and mortar.

Working out a design to fulfill a particular specification can be difficult for several reasons: 1. You may need to learn a bit more about the capabilities of your computer and your chosen programming language/environment to see what things it makes easy or difficult. 2. You may also need to learn some extra information about the problem or find a technique to solve it before you can work out how to build the program. 3. Finally, you may be able to think of several ways to build the program, but they will all have different strengths and weaknesses and so some choices will have to be made. We'll return to these problems a bit later on. For our calculator, we have a fairly comprehensive specification and since it is a fairly simple program we can turn the that quite easily into a design: 1. BEGIN 2. PRINT welcome message 3. PRINT instructions 4. PRINT [number]> 5. READ first_number 6. PRINT [+-/*]> 7. READ the_operator 8. PRINT [number]> 9. READ second_number 10. calculate result of using the_operator on the first_number and the second_number 11. PRINT result 12. END Here we assume that PRINT means 'put something on the screen' and READ means 'get something typed on the keyboard' - both fairly standard programming operations. Notice how step ten is actually hiding quite a complicated procedure. Although we (as humans) could work out which operator was which and do the appropriate arithmetic, the computer itself will need to be told exactly how to do this - but we'll leave that until the programming stage. Notice also how the design includes all of the important steps needed to fulfill our specification - but that does not go into too much unnecessary detail. This is called abstraction.

When your design is completed you should have a very clear idea of how the computer is going to fulfill your specification, which in turn meets your requirements, which in turn should solve your original problem.

Programming is then the task of describing your design to the computer: teaching it your way of solving the problem. There are usually three stages to writing a program: 1. Coding 2. Compiling 3. Debugging Coding Coding is the act of translating the design into an actual program, written in some form of programming language. This is the step where you actually have to sit down at the computer and type! Coding is a little bit like writing an essay (but don't let that put you off). In most cases you write your program using something a bit like a word processor. And, like essays, there are certain things that you always need to include in your program (a bit like titles, contents pages, introductions, references etc.). But we will look at them later. When you've finished translating your design into a program (usually filling in lots of details in the process) you need to submit it to the computer to see what it makes of it.

As an example, we shall develop and present the code for the calculator later on. Compiling Compilation is actually the process of turning the program written in some programming language into the instructions made up of 0's and 1's that the computer can actually follow. This is necessary because the chip that makes your computer work only understands binary machine code - something that most humans would have a great deal of trouble using since it looks something like:
01110110 01101101 10101111 00110000 00010101

Early programmers (like me) actually used to write programs in that sort of a style - but luckily they soon learnt how to create programs that could take something written in a more understandable language and translate it into this gobbledy gook. These programs are called compilers and you can think of them simply as translators that can read a programming language, translate it and write out the corresponding machine code. Compilers are notoriously pedantic though - if you don't write very correct programs, they will complain. Think of them as the strictest sort of English teacher, who picks you up on every single missing comma, misplaced apostrophe and grammatical error.

This is where debugging makes it first appearance, since once the compiler has looked at your program it is likely to come back to you with a list of mistakes as long as your arm. Don't worry though, as this is perfectly normal - even the most experienced programmers make blunders. Debugging is simply the task of looking at the original program, identifying the mistakes, correcting the code and recompiling it. This cycle of code compile debug will often be repeated many times before the compiler is happy with it. Luckily, the compiler never ever gets cross during this process - the programmer on the other hand... It should also be said at this point that it isn't actually necessary to write the entire program before you start to compile and debug it. In most cases it is better to write a small section of the code first, get that to work, and then move on to the next stage. This reduces the amount of code that needs to be debugged each time and generally creates a good feeling of "getting there" as each section is completed. Finally though, the compiler will present you with a program that the computer can run: hopefully, your solution!

The final step in the grand programming process is that of testing your creation to check that it does what you wanted it to do. This step is unfortunately necessary because although the compiler has checked that your program is correctly written, it can't check whether what you've written actually solves your original problem. This is because it is quite possible to write a sentence in any language that is perfectly formed with regards to the language that it's written in (syntactically correct) but at the same time be utter nonsense (semantically incorrect). For example, 'Fish trousers go sideways.' is a great sentence - it's got a capital letter and a full stop - but it doesn't mean a lot. Similarly, 'Put the ice cube tray in the oven.' has verbs and nouns and so on - but it's pretty useless if you wanted to make ice cubes.

So your program needs to be tested, and this is often initially done informally (or perhaps, haphazardly) by running it and playing with it for a bit to see if it seems to be working correctly. After this has been done, it should also be checked more thoroughly by subjecting it to carefully worked out set of tests that put it through its paces, and check that it meets the requirements and specification. - but we shall discuss this more later on in the book. Where mistakes are identified, it is a case of donning a Sherlock Holmes hat and trying to figure out where in the code the mistake is. Once identified, the problem should be fixed by changing the code and recompiling. Care should be taken at this point that this fix doesn't break something else, so careful retesting is important. This process is also known as debugging. Once all the testing and debugging has been completed, you should be pretty certain that your program works according to your requirements and your specification and so you should finally have a solution to your problem! Easy isn't it?!

1. Identify the Problem - What Are You Trying To Do? o Requirements o Specification 2. Design a Solution - How Is It Going To Be Done? 3. Write the Program - Teaching the Computer o Code o Compile o Debug 4. Check the Solution - Testing it Understands You While this may sound like a great deal of effort to go to build a simple program, don't worry, as after a while it will become second nature, and for small programs, most of the stages can be done in your head. The next section will introduce you to your first programming language, and your very first program!

Your First Program

There comes a time in every programming lesson where you have got to stop talking in general about things and cut straight to the code. But before we do that, we've got to choose a particular programming language to use. There are hundreds of programming languages to choose from (maybe more) - the more popular ones that you might have heard of are C, C++, Smalltalk, Squeak, Pascal, Delphi,

Basic, Visual Basic, Eiffel, Ada, Cobol, Perl, Python, Fortran, Logo, Lisp, Scheme, Prolog and Haskell. The list goes on into ever more surreally chosen words and acronyms, each with different strengths and weaknesses and its own crowd of fanatical supporters. The one we're going to use to illustrate the concepts in this lesson is called Java. It's caused quite a stir in the programming community recently because it has several very nice features that make it ideal for writing programs for the internet. It is very popular, powerful and easier than C++.

Hello World
In a tradition that goes back many tens of years, your first program will be called "Hello World". Its requirements are simple - it must be simple. Its specification is simple - when run, it will display the words "Hello World!". Its design is simple - BEGIN, PRINT "Hello World!", END. And here's the code:
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }

Well it's almost simple... You can think of the first line as telling the computer what you're going to call your program. In actual fact it does a little bit more than that - but again, we'll come back to that later. The second line is just a squiggly bracket, or brace to give it it's technical name. Braces always come in pairs: an open and a close brace; a brace of braces. They mark the beginning and end of a block of code of some sort. In this case the closing brace of this pair is the one on the last line of the code and they mark the beginning and end of the program. The third line is rather more complicated to look at, but actually, it's simply a marker to tell the computer where to start from - the main entry point. They could have used something like 'Hey Computer, Start HERE!' instead. The fourth line is another brace that marks where to begin obeying the programs instructions. The computer will start at that brace and do everything you tell it to until it reaches the corresponding close brace (on the second to last line) and then it will stop. This set of instructions is referred to as the main method (or sometimes as main function or main procedure) because it's where everything happens.

The fifth line contains the meat of our program - it's a line that tells the computer 'System' to display a line of text 'out.println'. The bit in the round brackets (or parentheses) and the double quotation marks tells it what to display: 'Hello World!'. And then finally the semicolon (;) tells the computer that that's the end of that instruction and that it should look for another. Java uses semi-colons like we use full-stops. The next line though is the closing brace of the main method, and so the program will end. The final line just ends the program definition. You're now going to have a go at compiling and running this program at least testing whether it works should be simple. Compiling and Running At this point it is very difficult to give you accurate information about how to do this, as it will depend greatly on what sort of computer system you are using and who set it up. However, I'll give it a try and if you get stuck ask somebody who looks like they know what they're doing to help you - but watch everything they do and take careful notes. Then next time, and every time afterwards, you'll be able to look like you know what you're doing too! There are four stages to this process: 1. 2. 3. 4. Setting Up Your Java Environment Saving the Program in a Source File Compiling the Source File Running the Compiled Program

I'm going to give three different explanations, one for using the Java Development Kit on a Unix workstation, one for using the Java Development Kit on a PC running Windows 95 or NT, and one very vague one about how to use a Java Development Environment like Java Workshop, Visual Cafe or Visual J++. Setting Up Your Java Environment The first thing you will need to do is set up your Java environment - this step basically involves telling your computer where it can find the Java compiler and other bits and bobs. You usually only have to do this once per programming session. Unix In an xterm window, at the prompt (which should look something like a greater than (>)

or percent (%) sign) type:

setup Java On other Unix systems you may have to type something like source /usr/scripts/JavaSetup or setenv PATH ${PATH}:/usr/java/bin

Windows 95/NT Depending on how Java is installed on your computer, you may find that your Java environment is set up automatically (through the use of autoexec.bat or NT environment variables for those who need to know the details). However, if it's not you will need to get someone 'who knows PCs' to help you set things up. In either case, you'll need to open a window that you can type commands into: use Start...->Programs to start either an MS-DOS Prompt (on Win95) or a Command Prompt (on WinNT). Type doskey and press RETURN - this will help you to correct mistakes in your typing more easily. For the adventurous among you who don't have their environment set up automatically, you'll need to type something like set PATH=%PATH;C:\jdk\bin. Development Environment This one's easy - just start your development environment. Saving the Program in a Source File The second thing you need to do is to create a text file with your program in it. This is where you need to use a text processor - this is a bit like a word processor in that you can type and edit words in it, but it won't let you do things like use different fonts or centre stuff. For Java, you need to note that the source file needs to have the same name as your program, except with ".java" tagged on the end. So for our HelloWorld program, we need to save the file as "". Unix Start a text editor - you could use something like xemacs, textedit or axe. To start them, type their name at the xterm prompt. Create a new document, and type (or copy and paste using the middle mouse button) the program into it, save the document under the appropriate filename. Make sure you know where you've saved it to - which directory it's been saved into.

Windows 95/NT Again, start a text editor like Accessories->Notepad or TextPad (which can be downloaded from the Internet). Again, type or copy and paste the program into a new document and save it with the appropriate name. Again make sure you note where you've saved it - which folder was it saved into. Development Environment This one's slightly more complicated. Most development environments like you to create a new project for each new program you wish to write, so try to find a menu item like that. Then when it asks you what to call the project, tell it the name of the program (without the ".java" bit). Also, look closely at what type of project it's going to create for you - it'll probably give you a choice and it's most likely to default to something called an "applet". You want to change that type to a "Java Application" or something similar. You also don't want it to give you an Graphical User Interface (GUI) or use the Abstract Windowing Toolkit (AWT) yet - you're only going to be using simple console input and output for now. Once you've done that and clicked okay, it'll save it and open up a barrage of windows one of those should be the text editor (with the title "", and if you're lucky, it may already have written some of your program for you. Type, or copy and paste the rest into place and save it. Compiling the Source File This is the point at which you submit your program to the compiler to translate it into computer-ese for you. When the compiler has finished running it should create you a file with the same name as your program, except with ".class" on the end. If it finds any errors, the compiler will print them on the screen and expect you to change the code and run it again. If you're feeling brave, try deleting things like the semi-colon on the third line or one of the braces to see what it does. Don't forget to put them back afterwards though. Unix You will need to find your xterm prompt again and change directory to the place that you've saved your program. To do this you might need to type something like:
cd /home/something/username/myjava

Type ls to list the files in that directory to check that your ".java" file is there. To find

out where you are - type pwd. Once you're in the right place, simply type:

If it complains with something like program "javac" not found or java.lang.Thread not found, things aren't setup properly - go back to stage one. If you're using xemacs, you may be able to type CTRL-C at this point and it'll do everything for you. Windows 95/NT You will need to return to your MS-DOS/Command Prompt (use the old one - if you start a new one, you will need to set it up again). Once there, you will need to change directory to the folder that contains your program. To do that you will probably have to do something like:
cd C:\MyJava

Type dir to see a directory listing to check that your ".java" file is there. It should say where you are to the left of the > prompt. Once you're in the right place, simply type:

If it complains with something like bad command or file name or java.lang.Thread not found, things aren't setup properly - go back to stage one. Development Environment This one's easy - you should find a menu item or button labelled "Compile" - just choose that. There should be a window in which the results of the compilation (and any errors) are displayed. Running the Compiled Program You should now have a compiled program sitting in a ".class" file somewhere - you can try loading it into a text editor to see what it looks like if you're curious. Now what we need to do is tell the computer to run this code. With most programming languages, this would be simply a case of typing in the name of the program and the computer would

load up the program, point its silicon chip at the main entry point and everything would just run. Java, however, is a platform independent language - which means it is able to run on any sort of computer with any sort of chip in it - a kind of Esperanto for computers. To pull off this trick, Java programs actually run on a virtual machine - a pretend silicon chip which is the same everywhere. You can think of it as a program that hypnotises the real silicon chip so that it can speak a different, standard, language. So when you run a Java program, you have to point the real silicon chip at the Java virtual machine, and the Java virtual machine at your class file. Unix Again, find your xterm and make sure you're in the same directory as the ".class" file. Then type:
java HelloWorld

Windows 95/NT Go back to your MS-DOS/Command Prompt and check that you're in the same folder as the ".class" file. Then type:
java HelloWorld

Development Environment You should find a menu item called "Run" or "Execute" - choose that! Try removing semi-colon & braces. Try getting it to print hello name Try underlining your name with minus signs: ----Try getting it to print hello to all of your friends

We are about to study the idea of a computational process. Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a program. People create programs to direct processes. In effect, we conjure the spirits of the computer with our spells. A computational process is indeed much like a sorcerer's idea of a spirit. It cannot be seen or touched. It is not composed of matter at all. However, it is very real. It can perform intellectual work. It can answer questions. It can affect the world by disbursing money at a bank or by controlling a robot arm in a factory. The programs we use to conjure

processes are like a sorcerer's spells. They are carefully composed from symbolic expressions in arcane and esoteric programming languages that prescribe the tasks we want our processes to perform.

Programming Fundamentals
Variables are one of the most important things that you will use in a computer program. You can think of them as a box, container or pigeon-hole that you can store information in. You can then retrieve that information for later use. When you create a variable you give it a name, and that is what you use to refer to the box when you want to use it. Type In most programming languages variables are typed. This basically means that the "box" can contain only one type of information. Once a variable has been created with a specific type, it cannot be used to store anything else. It is similar to being able to create different sized and shaped boxes, say one for parcels and one for letters. For example, in Java and C++ we can create a box called myNumber to put a number in, by using the following line of code:
int myNumber;

We can then assign a value to that variable, i.e. put a value into that box, by using the following piece of code:
myNumber = 5;

This basically tells the computer to store the value 5 into the box called myNumber. We can then use the value stored in that variable when we need it. For example, we might want to print it out
System.out.println( myNumber ); cout << myNumber << endl; // Java // C++

Or use it as part of a different calculation:

myResult = myNumber + 3 * 10;

Strings One particular type of variable that you will find very useful, but that has a slightly peculiar name, is the String. A string is just a box that can hold arbitrary quantities of text. So you can define strings to hold names, sentences, paragraphs or entire essays.

You define strings in your code by surrounding them with double quote ( ") marks. You have to do this to differentiate them from the surrounding code. In Java you would use Strings in the following way:
String myName; myName = "Andy"; System.out.println( myName );

In C++ you would use:

String myName; myName = "Andy"; cout << myName << endl;

In the most basic sense, a computer program is just a simple list of instructions that tell the computer how to do something. All that you are doing when you run a program is just giving the chip inside the machine that list of instructions, and telling it to follow them. So that the computer knows where to start with your list of instructions, both Java and C+ + define a main entry point. This is where you should start to describe your list of instructions - your program. In Java, this main entry point looks like this:
public static void main( String[] args ) { // your program starts here }

In C++, the main entry point looks like this:

int main() { // your program starts here }

You would then start to describe those list of instructions inside the braces or squiggly brackets ({ and }). For example, we could write some code to create a variable, store a value in it and then print it out:
public static void main( String[] args ) { int luckyNum; luckyNum = 7; System.out.println( luckyNum ); } // Java

int main() { int luckyNum; luckyNum = 7; cout << luckyNum << endl; }

// C++

If you actually want to compile these, you will need a couple of extra lines of code, which are not included here.

It is possible to write quite useful programs by writing simple lists of instructions, but really useful programs need to cope with lots of different situations. For example, think about writing a hypothetical program to make a cup of coffee. You might come up with something like:

However, what happens to this program when the kettle is empty? It won't work properly, so we need a way of checking for particular circumstances and dealing with them:

To do this sort of thing, you can use the conditional statements supported by Java and C+ +. In particular the if...else statement. For example, you might want to print a message that depends on the value of a particular number, in Java you would use:
if ( number == 5 ) System.out.println( "SNAP!" ); else System.out.println( "Not snap." );

In C++:
if ( number == 5 ) cout << "SNAP!" << endl; else cout << "Not snap." << endl;

In both cases note the use of the double equals signs ( ==) as opposed to the single equals sign (=). Single equals means assignment (i.e. make this equal to). Double equals is an equality check (i.e. is this equal to?).

The other problem with our coffee making example is that we actually don't check that the kettle has boiled before we add the water, so it might still be quite cold! We need to repeatedly check to see if the water has boiled:

In Java and C++, we can tell the program how to do repetitive things by using its loop statements. In particular the while and for loops. There are actually two types of while loops, and the only difference is where the check is done. When programming, it's always a good idea to think of the program you want to create in terms of its solution. In order to do this, you must have a pretty solid understanding of the programming language that you'll be working in and what you can do with it. Then you should sort out what exactly you're trying to accomplish. What do you want your program to do? What problem is it solving? Next, divide the program into its various components. Then decide how those components will fit together to execute the program. Once you have all this sorted out, you can write each part of the program and put them together. Some of you eager beavers might want to start coding right away, but this can result in a messy program and lot of frustration for you down the road. If you don't plan ahead, you won't have a clear idea of what exactly you need to do to complete the program, and this can lead to a lot of mistakes. Establishing this type of process from the get-go is important because it makes it easier when you need to tackle more complex problems. No matter what language you're working with, you'll always use variables. Variables are like saved documents on your computer, each one storing information. When you name a variable you are actually declaring or defining it. The values stored in them can then be applied to functions (we will get to them later on). In JavaScript, for example, variables can hold letters, numbers, and Boolean (true or false) values. If you want to access the information that a variable has stored in it, all you have to do is call the variable's name. The process of naming a variable is unique to the programming language, but a few universal rules hold true. First, never give a variable the same name as a function; this can cause confusion. You can easily lose track of which is doing what. Second, make

sure the names are descriptive. Stay away from abstract names so that when you or someone else goes back over the code, the purpose of the variable isn't misunderstood. You may have to define variables before defining the function that you call them in, depending on the language you're using. In JavaScript, it's always good practice to go ahead and define them beforehand to prevent having to root through a bunch of code to see what isn't defined. They can be defined between the head tags or in the body.

Scope of variables
The scope of a variable refers to when and where a variable can be used, and they fall into two groups: local and global. Local variables are used most often in user-defined functions. If you try to call a local variable outside of its specific function, you will either get an error or the computer will evaluate the global variable instead (if the local variable has the same name as a global variable). The scope of a global variable is anywhere at any time. They exist outside of any functions regardless of whether they are called in one. You can create new variables with var. If you had a function named "Squiggly" and you used var to define the variable "Gobbledygook" within it, Gobbledygook would be a local variable, and would only be relevant inside Squiggly. Now, if you used var to define a variable called "Gibberish,", just by itself with no association to a function, it would be a global variable. It's not specific to one function but rather can be applied to any function at any time. An important thing to note is that global variables take precedence over local variables. So, if you call Gobbledygook within Squiggly, but there is also a global variable with the same name being applied to the function, the value of the global variable will be evaluated instead. Conditionals or Else If and if-then statements are commonly used conditionals in most programming languages. They check a condition and then take the appropriate action based on whether the condition is true or false. The basic structure of an if-then statement is:
if (condition) { (action); } else { (else-action); }

Conditionals always start with the word if. If the condition is true, then the action within the body is applied and the appropriate results are produced. It's possible for more than one action to be applied. If the condition is false, then else-action, also in the body, is applied and produces the appropriate return value.

The if statement only evaluates whether a condition is true, and then proceeds to the next condition or line of code. The nice thing about using an if-else instead is that you have more control over the flow of the program. In addition, the else allows you to create command blocks (grouped commands) when the condition is false. This eliminates the work of writing several if statements to create a command block since they can all be combined and listed inside the else statement. Predicates, or conditional operators as they're called in JavaScript, are functions that return true or false values. They are frequently used in conditionals and can evaluate to one or two different values depending on the condition. Sometimes it's easier to use a conditional operator than an if-then statement. Other times, they are used in conjunction with the if-then statements to produce the desired results. It all depends on the situation. You can usually identify them by the question mark that they end with. The structure for conditional operators is as follows: (condition) ? val1 : val2 Let's say you wanted to create a function called printName that checked to see if the variable name is equal to "Deeter" and then returned something accordingly. If name is not equal to "Deeter" then the function would return something else. Here's what it would look like: function printName(name) { alert((name == "Deeter")?"The monkey likes Deeter":"Who invited you to this party?"); } Looping is often used for actions like counting through a list and applying a certain function to each element in that list, or testing for a condition and repeating the process until the condition is false. It essentially allows a program to repeat pieces of the code. For example, a loop could be used to repeat a sequence of actions on each number between 1 and 8, or it could continue to collect information from a user until it's indicated that the user is done. The two main kinds of loops are conditionals (like the while loop in JavaScript) and iterated (the for and for in loops in JavaScript). You'll usually encounter iterated loops, so I'll focus on them. As I stated earlier, they are mainly used for counting purposes. For in is for more specific applications. It sifts through the properties of an object, which is useful when you don't know the number of properties. Here's the basic structure for a loop:
for (initial value; test; increment) { do this stuff; }

Here's a loop as it might be used in a function:

for (i=0; i < thePasswords.length; i=i+1) { if (enteredPassword == thePasswords[i]) passwordMatches = true; } return passwordMatches; Let's break down the loop into three parts so it's easier to understand. The first part of the for loop (i=0) sets its initial value. In this case, the initial value is 0. The second part, i < thepasswords.length, is evaluated until the return value is false. The third part says what to do to i each time the loop runs. When part two is not true, the looping will stop. The function will return false if enteredPassword doesn't match any of thePasswords[i]. The if statement just says if your password matches i, then change the value of passwordMatches to true, which in turn makes the getPassword function true. What's A Function? Any JavaScript, C++, or Perl program is built with functions. Functions are expressions that execute an operation, allowing a programmer to create several pieces of code and bunch them together to perform a particular task. Functions accept information in the form of arguments (the values that are passed through the function) and evaluate the arguments to provide results. It's important to prevent mix-ups by differentiating between arguments and parameters. These terms are often used interchangeably, which has always been especially confusing. So, to make things clearer, when we say arguments we will be referring to functions. Likewise, when we say parameters, we will be referring to programs. Arguments are created whenever a function is defined. They are basically placeholders for the values that will be passed through the function. When an argument is passed through the function, it is evaluated and then applied to the function, which gives you a return value (the results). Arguments exist only during the life a function and change every time it is called again because the values passed through them also change. The parts of a function are the function name, the argument(s), and the body. It looks something like this: function printName(argument) { body (all the cool code) } The function name is printName and it takes in one argument. The stuff between the two curly brackets is the body and that's where all the code goes. There are two types of functions, built-in and user-defined. Built-in functions are the functions that already exist within the language. An example of this in JavaScript would be alert () ordocument.write(). User-defined functions are functions that the programmer creates. They are defined by assigning a name to the function and executed by calling that

name again. The exact process of defining them varies from language to language. In JavaScript, you begin with function. Let's look at a function that combines everything we have learned so far. Basically, when you enter the page, you type in a password and get a response according to whether or not the password is correct. The code would look like this: function getPassword () { thePasswords = new Array('foo','bar','bobo'); var passwordMatches = false; var enteredPassword = prompt ("Enter your password:"); for (i=0; i < thePasswords.length; i=i+1) { if (enteredPassword == thePasswords[i]) passwordMatches = true; } return passwordMatches; } var theVerdict = getPassword(); if(theVerdict == true) { alert("Right-O!") } else { alert("How much schooling did you say you had?"); } As soon as you type in a password it becomes the value of the variable enteredPassword. If you type in a password - "bobo" for example - the function sifts through the array (thePasswords) and compares each of the elements to the password you typed in. If it finds a match, the value of the variable passwordMatches changes to true, which also makes the function getPassword true, so you would then get a pleasant little message. If you type in a password like "spivey," the function would be false because it doesn't match an element in the array, so the value of passwordMatches (which is initially false) would not change. In the loop in this function, the initial value of the variable i is 0. Each time the loop moves to a different element in the array, it adds one to the value of i. This is due to the i=i+1 piece of the loop. The position of each new element is one more than the last. If i=2 or thePasswords[2], then it would compare your password to "bobo" in the array list because that is the second position in the list (the third counting from 0). Basically, thePasswords[2] is equal to "bobo." If there was another element in the list after "bobo," it would be referred to as thePasswords[3], since it would be the fourth position in the array. So, if i=0 and the corresponding element in the array does not match your password, it will continue to sift through the rest of the list and compare. As long as i < thePasswords.length is true, the loop will continue to add one to i and compare until the

expression returns false (when i is greater than or equal to thepassword.length). If i < thePasswords.length is false, the function will return whatever value passwordMatches is set to - which could be either true or false. If passwordMatches is false then you'll receive a not-so-pleasant message. Hints, Tips, and Tricks There are a few final things to consider when writing programs. You may have noticed that the example codes here have a fair amount of spacing between the commands. This spacing isn't essential, but in my opinion, it makes the code much easier to read and understand. If you're having trouble working through the code, and you're not sure what you need to complete the program, try writing pseudo code, which is a mixture of English and the programming language. It's very helpful to write out the steps you need to create a program, and sometimes it's easier to articulate them in English rather than in some abstract programming language. It's also important to debug your program as you work on it. Don't wait until the whole program is finished and then check to see if it works. Check each part as you go and make sure each one works properly before moving on to the next piece. This will save you a lot of time and unnecessary stress. And remember, you are going to make mistakes, and that's OK. Professional programmers spend half of their time debugging; it's part of the learning process. Last but not least, have fun! Experiment, get frustrated, and then experiment some more. No pain, no gain. ******************