chapter 1 - introduction to programming and flowcharting

Upload: ramachandran-nambissan-tm

Post on 14-Apr-2018

239 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    1/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 whichthey 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 startingconstruction 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 theAmerican 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 communicationbetween 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 writethe 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 arefrequently 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 beinitially 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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    2/33

    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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    3/33

    = 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 allowtracing 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 pagenumbers. You may find it helpful when you develop flowcharts. If you don't have this

    form available, a plain piece of paper will do.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    4/33

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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    5/33

    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, detailedsequential 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 Definitionin the following figure.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    6/33

    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 infigure. 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. Thisstep 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 topto 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 annotationsymbol 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 makeit more effective and better way of communication.

    i. Ensure that the flowchart has a logicalstartandfinish.

    j. It is useful to test the validity of the flowchart by passing through it with a simpletest 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    7/33

    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 systemsanalysis and program development phase.

    5. Proper Debugging: The flowchart helps in debugging process.

    6. Efficient Program Maintenance: The maintenance of operating program becomeseasy 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. A program flowchart indicates the_________ to be performed and the

    __________ in which they occur.

    ii. A program flowchart is generally read from _____________ to

    ________________iii. Flowcharting symbols are connected together by means of

    ___________________iv. A decision symbol may be used in determining the ____________ or

    ___________ of two data items.

    v. __________ are used to join remote portions of a flowchart.

    vi. ____________ connectors are used when a flowchart ends on one page andbegins again on other page

    vii. A ________ symbol in used at the beginning and end of a flowchart.

    viii. The flowchart is one of the best ways of ________ a program..ix. To construct a flowchart, one must adhere to prescribed symbols provided by the

    __________ .

    x. The programmer uses a ____________ to aid him in drawing flowchart symbols.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    8/33

    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 technicalanswer. 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 addedbenefit 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 aboutprogrammers 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 thewords 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 thesecond 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 soon.

    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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    9/33

    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 hadto 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 momentthat 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, Ithink 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, toinclude 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 thinkingabout 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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    10/33

    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, youmight 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 (whichis 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 thatthey'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 computerswhat 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 takea 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 away, 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 orderto make your computer do anything even vaguely impressive. But don't worry; there aresome 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    11/33

    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, andit'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 saveyourself 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 ofcomputer 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 enoughconfidence and knowledge to go on to explore the rest of this fascinating world all byyourself.

    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 tocreate 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 justsay 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 anythingyou 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 ofdirections 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 verycomplex 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    12/33

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

    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. Identify the Problem

    2. Design a Solution3. Write the Program

    4. 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 whatit is that you're trying achieve.

    There are two stages to identifying a solution:

    Requirements

    Specification

    Requirements

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    13/33

    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 willbe requiredto do.

    For example, if we were asked to write a calculator program, we could choose manydifferent 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 thenit 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 sums correctly

    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 programwe 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 or152.

    Specification

    The second step is to then look at the list of requirements and to decide exactly what yoursolution 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    14/33

    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 shouldalso 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 ofwhat 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 spellout 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 morecomplicated 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    15/33

    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 andyour 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 fairlysimple program we can turn the that quite easily into a design:

    1. BEGIN

    2. PRINT welcome message

    3. PRINT instructions4. PRINT[number]>

    5. READ first_number

    6. PRINT[+-/*]>

    7. READ the_operator

    8. PRINT[number]>

    9. READ second_number10. calculate result of using the_operator on

    the first_number and the second_number11. PRINT result12. END

    Here we assume thatPRINTmeans 'put something on the screen' andREAD 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 (ashumans) 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 ourspecification - but that does not go into too much unnecessary detail. This is called

    abstraction.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    16/33

    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.

    Program

    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. Coding2. 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 thecomputer 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 actuallyfollow. This is necessary because the chip that makes your computer work only

    understands binary machine code - something that most humans would have a great dealof trouble using since it looks something like:

    01110110

    01101101

    10101111

    00110000

    00010101

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    17/33

    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 programsare 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 youup on every single missing comma, misplaced apostrophe and grammatical error.

    Debugging

    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 programmersmake 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 neverever 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. Thisreduces 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!

    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 checkwhether 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 perfectlyformed 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 gosideways.' 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    18/33

    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 thoroughlyby 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 tofigure 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 knownas 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?!

    Summary

    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 Computero Code

    o Compile

    o Debug4. 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 tochoose 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,

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    19/33

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

    The one we're going to use to illustrate the concepts in this lesson is called Java. It'scaused 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 - whenrun, 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 yourprogram. 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. Bracesalways 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 theprogram.

    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 usedsomething 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 functionor main procedure) because it's where everything happens.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    20/33

    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 semi-colon (;) 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, asit 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. Setting Up Your Java Environment

    2. Saving the Program in a Source File

    3. Compiling the Source File4. 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 Windows95 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 andbobs. 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 (>)

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    21/33

    or percent (%) sign) type:

    setup Java

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

    Windows 95/NT

    Depending on how Java is installed on your computer, you may find that your Javaenvironment 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 anMS-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 iswhere 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 needto save the file as "HelloWorld.java".

    Unix

    Start a text editor - you could use something like xemacs, textedit oraxe. 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 underthe appropriate filename. Make sure you know where you've saved it to - which directory

    it's been saved into.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    22/33

    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 createa 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 togive 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 "HelloWorld.java", and if you're

    lucky, it may already have written some of your program for you. Type, or copy andpaste 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 anyerrors, 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 afterwardsthough.

    Unix

    You will need to find your xterm prompt again and change directory to the place thatyou'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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    23/33

    out where you are - type pwd.

    Once you're in the right place, simply type:

    javac HelloWorld.java

    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 directoryto 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:

    javac HelloWorld.java

    If it complains with something like bad command or file name or java.lang.Thread notfound, 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 choosethat. 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 weneed 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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    24/33

    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 anysort 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 chipwhich 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 Javaprogram, 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 rulescalled 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 performintellectual 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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    25/33

    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

    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 yougive 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 aspecific 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 ); // Java

    cout

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    26/33

    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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    27/33

    int main() // C++

    {

    int luckyNum;

    luckyNum = 7;

    cout

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    28/33

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

    Loops

    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:

    IF KETTLE IS EMPTY THEN

    FILL KETTLE FROM TAP

    SWITCH KETTLE ON

    PUT TEASPOON OF COFFEE POWDER IN CUP

    WHILE KETTLE HAS NOT BOILED THEN

    WAIT

    ADD WATER FROM KETTLE

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

    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 theprogramming 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 variouscomponents. 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 planahead, 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 complexproblems.

    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 beapplied 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

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    29/33

    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 tosee 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-definedfunctions. 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 atany 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 toany 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 morethan 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.

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    30/33

    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 createcommand blocks (grouped commands) when the condition is false. This eliminates thework 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 thatreturn 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 conjunctionwith 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 certainfunction 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 indicatedthat 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 inis 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;

    }

  • 7/29/2019 Chapter 1 - Introduction to Programming and Flowcharting

    31/33

    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