Programming: Concepts for new

How to Use this User Guide

This handbook accompanies the taught sessions for the course. Each section contains a brief overview of a topic for your reference and then one or more exercises. Exercises are arranged as follows:  A title and brief overview of the tasks to be carried out;  A numbered set of tasks, together with a brief description of each; Some exercises, particularly those within the same section, assume that you have completed earlier exercises. If you have any problems with the text or the exercises, please ask the teacher or one of the demonstrators for help. Many of the exercises used here are designed to be worked through in pairs or small groups of students, to encourage discussion about the topics covered. Software Used

None Files Used

None Revision Information

Version Date Author Changes made 1.0 Sept 2006 Dave Baker Created 1.1 May 2007 Dave Baker Minor typo corrections Rename of Chapter 6, with change of focus 1.1a Nov 2007 Dave Baker Correction of typos in Ex 6 1.2 Dec 2007 Dave Baker Revision of some exercises 1.3 April 2011 Dave Baker Revision/removal of some exercises 1.3a Oct 2011 Dave Baker Minor corrections 1.4 Oct 2012 Dave Baker Minor updates 1.5 Sep 2013 Dave Baker Revision of some exercises 1.6 Feb 2014 Dave Baker Added section on code re- use 1.7 Jun 2014 Dave Baker Added section on lists 1.8 Oct 2016 Duncan Young Updates to University names and language descriptions in Section 7

Acknowledgements

Many of the ideas in this module have been talked through with colleagues and friends, in particular Jonathan Gregory formally of Abingdon College of Further Education. Thanks to Peet Morris of the Computing Laboratory (ComLab) at Oxford University for his useful suggestions and for keeping me on the straight and narrow in terms of the underlying theory of computer programming and computer languages. Copyright

This document is made available under a Creative Commons Attribution- NonCommercial-ShareAlike CC BY-NC-SA licence by Dave Baker who asserts his right to be identified as the author. Note that some images used in the document and presentations are copyright of their owners and may be subject to different copyright conditions. Where possible

IT Learning Centre iv this has been noted in the text. If an error in attribution/copyright has been made, contact the author who will be pleased to make the necessary corrections.

v IT Learning Centre Contents

1 Introduction ...... 1 1.1. What you should already know ...... 1 1.2. What you will learn ...... 1 2 What is a Program? ...... 2 2.1. Where do we find programs? ...... 3 2.2. Where do programs come from? ...... 3 2.3. So, what’s so difficult about programming? ...... 6 2.3.1. Types of program errors ...... 6 2.3.2. The program development process...... 7 3 What is a computer language? ...... 9 3.1. Computer language structure ...... 11 3.2. Algorithms ...... 11 3.3. Pseudocode ...... 12 3.4. Pseudocode and comments ...... 13 4 Controlling how a program behaves ...... 17 4.1. Sequence ...... 17 4.2. Selection ...... 17 4.2.1. Nested selection ...... 18 4.2.2. Deeply nested selection ...... 18 4.3. Repetition...... 19 4.3.1. Pre-determined repetition...... 19 4.3.2. Conditional repetition ...... 19 5 Data ...... 23 5.1. What is a variable? ...... 23 5.2. What is a constant? ...... 24 5.3. The types of data ...... 25 5.4. Operators ...... 27 5.5. Data structures ...... 28 5.5.1. Arrays...... 28 5.5.2. Lists ...... 30 6 The ‘shape’ of programs ...... 32 6.1. Functions ...... 32 6.1.1. Argument (or Parameter) passing ...... 34 6.1.2. Re-use of code ...... 34

IT Learning Centre vi 6.2. Objects ...... 36 6.2.1. Encapsulation: Data and Behaviour ...... 37 7 What next? ...... 38 7.1. A hands on introduction using Alice ...... 38 7.2. Playing with SCRATCH ...... 38 7.3. An example of a Java program ...... 38 7.4. Choosing a computer language to learn ...... 41 7.5. ...... 41 7.6. C++ ...... 42 7.7. Java ...... 42 7.8. JavaScript...... 43 7.9. MatLab ...... 43 7.10. Perl ...... 44 7.11. PHP ...... 44 7.12. Python ...... 45 7.13. C# ...... 45 7.14. Objective-C ...... 46 7.15. Swift ...... 46 7.16. Visual Basic ...... 46 7.17. Ruby ...... 47 7.18. R ...... 47 7.19. Wolfram ...... 47 7.20. Haskell ...... 47 8 Glossary ...... 48

vii IT Learning Centre Exercises

Exercise 1 What is a program? ...... 2 Exercise 2 Simulating a program ...... 4 Exercise 3 Writing a program ...... 5 Exercise 4 An algorithm – Bubble sort ...... 14 Exercise 5 Creating your own algorithm – The Median ...... 15 Exercise 6 Efficient use of control structures ...... 21 Exercise 7 Identifying data types ...... 27 Exercise 8 Using a (arrays) ...... 29 Exercise 9 Using functions ...... 35

IT Learning Centre viii Programming: Concepts for new programmers PG002

1 IT Learning Centre

Programming: Concepts for new programmers PG002

1 Introduction Welcome to this introductory programming module. This booklet accompanies the module delivered by the University of Oxford IT Services, IT Learning Centre. Many of the exercises are designed to be worked in collaboration with other students in the class and so you will find that you will get the most out of it by attending a taught session rather than working through the booklet on your own. If at any time you are not clear about any aspect of the module, please make sure you ask your teacher or demonstrator for some help. If you are away from the class, you can get help by email from your teacher or from [email protected].

1.1. What you should already know This session is primarily for those of you who are interested in attending one of the other programming courses we offer at IT Services, but who have had absolutely no exposure to programming before. Therefore, nothing is assumed other than that you have an open and enquiring mind, and are willing to take part in some active class exercises. No computer programming is involved in this module!

1.2. What you will learn This module will introduce you to the most important concepts underlying programming in (almost) any computer language. It will introduce these concepts in a non-technical way, independently of any specific computer . In fact, in this module you will not be using a computer at all. The concepts covered are:  What is a program?  What is a computer language?  How do we get computers to do what we want?  What is data?  How do programs reflect the real world? Or, to put that more technically:  Keywords, instructions and algorithms  Sequence, selection and iteration  Data, variables and constants  Functions, objects and methods At the end of this module, you will not be able to write a computer program! However, you should be more prepared for the jargon and concepts that you will encounter on one of the more formal programming courses in the IT Learning Centre.

1 IT Learning Centre PG002 Programming: Concepts for new programmers

2 What is a Program? Look around you. Hidden in the room (assuming that’s where you are) there are likely to be computing devices, of some sort. And each device will contain one or more programs, even if it is switched off. I carefully called them computing devices because a program does not need a computer in the common sense of the word. A program can exist in anything that can interpret a list of instructions and act on them. So, perhaps there we have the seed of a definition of a program: A list of instructions that can be understood and followed resulting in a predictable activity

Exercise 1 What is a program? Examine the list below. Which do you think could be classified as a program? Do you need to distinguish between what IS a program and what USES a program? The answers are not always straightforward and so you should discuss them with a fellow student. Write your conclusions and comments you have, in the space provided. A mechanical watch

The Radio Times (a TV listings magazine)

A recipe

A washing machine

A laboratory mouse in a maze

A crossword puzzle

A picture of a computer as a file on a memory stick/CD-ROM

A sheet of music for an orchestra

IT Learning Centre 2 Programming: Concepts for new programmers PG002

2.1. Where do we find programs? The Oxford English Dictionary has two definitions of program: A sequence of operations that a machine can be set to perform automatically and A series of coded instructions which when fed into a computer will automatically direct its operation in carrying out a specific task Would either of those definitions change your answers to Exercise 1? Both definitions suggest that in order to have meaning, a program exists in the context of a machine or a computer that is able to follow the instructions. In this module we will presume that we are interested in programs for computers. Clearly, to follow a list of instructions that is a program, it must be accessible to the computer. All computers have some form of store, usually referred to as memory (often a memory chip), which can hold one or more programs. How the program is held in this memory can be important, but we won’t concern ourselves with the detail here. What we will note though is that, depending on the computer, the contents of this memory store may be fixed or changeable. If the memory contents are fixed, the program is put into that memory when the computer or memory chip is built or manufactured. This type of memory is called Read Only Memory or ROM. From then on the program cannot be altered. If the memory store is able to be changed (usually referred to as Random Access memory or RAM), we have the opportunity to update or add programs at any time. The computer is then said to be programmable. We will come back to this concept of computer memory when we discuss what we mean by data later in this module.

2.2. Where do programs come from? Having discovered that programs can reside in a computer’s programmable memory, the next question we might reasonably ask is “How do they get there?” Programs are written by people like you and me (yes, really!). Although they may be planned and designed independently of a computer, there comes a stage when someone has to sit in front of a computer screen and type in the instructions that make up a program. To do this they use a program that ‘understands’ how programs should be written and which is then able to make them available to the same or another computer. There is a chicken and egg problem here of course – how did the program that helps us write programs get written? To grossly oversimplify the answer to that question, remember the ROM memory we discussed in the last section. A simple program can be built into the ROM which allows a more complex program to be put into the programmable memory (perhaps from a disk) which in turn might call upon the program-creating program to be put into memory. This process is sometimes referred to as bootstrapping.

3 IT Learning Centre PG002 Programming: Concepts for new programmers

Exercise 2 Simulating a program Computers have no innate understanding of a program. From the computer’s viewpoint, it is a list of instructions that are blindly followed. In this exercise, you will explore some of the problems that might arise from this.

Task 1 Pair up with another student in the class. Your teacher will give each of you a set of building blocks. Move your chairs so that you are sitting back to back. Nominate one person as ‘the program’. The other person is ‘the computer’ Task 2 Using the blocks supplied, ‘the program’ should construct a simple model or shape. Using ordinary English and without showing the structure to ‘the computer’, ‘the program’ should describe to the computer how to build the structure. Important: The computer cannot ask the program any questions! It must just do what it is told. Task 3 When you have finished compare the two models.

Is the result what you expected?

Was the task difficult?

What effect did not being able to ask questions have on the task?

Is this a realistic representation of how programs and computers interact?

IT Learning Centre 4 Programming: Concepts for new programmers PG002

Exercise 3 Writing a program There is nothing magical about writing a program; you use a predefined language to prepare a list of instructions to be followed, one after the other.

Task 1 Using only the words given below (as many times as you like), write a list of instructions to guide someone from the lecture room door to your seat. Step Forward Backward Turn Left Right Sit Stand Stop

Task 2 Give your instructions to someone else in the class to follow. Does that person end up in your seat?

5 IT Learning Centre PG002 Programming: Concepts for new programmers

2.3. So, what’s so difficult about programming? Simple programs are easy to write; although it should be said that even these simple programs will more often than not contain mistakes. Let’s restate again – computers do not understand your program, they blindly follow the instructions you give them. This means that you have to be absolutely precise in the list of instructions that you give, and completely logical in the way you specify the tasks to be carried out. It is human nature not to be absolutely precise and logical, as you may have discovered in the previous exercises. This means that when we write a program, it will initially contain errors that we only discover when we try the program out. Once we have found an error, we can return to the list of instructions and correct them. This cycle of writing, testing, rewriting and retesting underlies the activity that is usually referred to as programming. Errors in programs are commonly called bugs, and removing of bugs is not surprisingly called debugging.

2.3.1. Types of program errors Without getting too technical, there are four common types of error that might occur in a program. Looking back over what you did in Exercise 2 and Exercise 3 you might be able to identify examples of the following: Syntax errors Programs are written in a particular language (your choice from very many) and languages have certain rules of use. In spoken English these rules are quite flexible, in written English less so. However, in a computer language you must conform exactly to the rules of the language (syntax) or the computer will not be able to follow your instructions. Most computer languages have a means for checking the syntax of your program, often as part of a program called a compiler, and will highlight what is wrong (but not usually how to fix it!). Run-time errors When a program is following your list of instructions, the program is said to be running or executing. At this run-time, something may happen which causes the program to fail. These run-time errors are often predictable in the sense that they could be foreseen. For example, it would be a mistake for the program to try and save information to a disk if the disk wasn’t present. Good programmers would always check the disk was available before trying to use it, but even the best programmers make mistakes. Logic errors A perfectly crafted program with no syntax errors, and with all possible run-time errors correctly catered for, may still not do what you want or expect. Let’s repeat one more time: computers do not understand your program – they blindly follow your instructions. Let’s take an extreme example. You have written a program to guide a robot around a building. The robot gets to a doorway, and goes through it. If you forgot to add the instruction to ‘open the door’, then the robot will crash into it!

IT Learning Centre 6 Programming: Concepts for new programmers PG002

So a logic error occurs where a step has been missed out or placed in the wrong order. Semantic Errors A semantic error is similar to a logic error, but with a subtle difference. Take the example of calculating the result of:

3 + 4 * 5 We might mean that we should add 3 and 4 and then multiply by 5 to get 35. The computer on the other hand might multiply 4 and 5 and then add 3 to get 23. Both could be considered correct, but in fact it is the second answer that is invariably calculated by programming languages. This is because programming languages are unambiguous (multiplication is defined as happening before addition), whereas human thought is often not!

2.3.2. The program development process Creating error free programs is not an easy task; some would say that for a program of any significance it is near impossible. There are a number of techniques that can help reduce the incidence of errors. These are all part of what can be referred to as the program development process, or more often software development process. In this short module we don’t have time to describe in detail what the techniques and processes are; in fact there are many different competing processes each with their supporters and detractors. There are a number of stages which are common to most processes. Analysis Deciding what the problem is. Design Designing how the problem can best be solved. Build Writing the program(s). Test Checking that the programs work as expected. Deliver Making the program available to the people who are to use it. Maintain Fixing any problems that appear while the program is being used, and perhaps adapting it to a suit a new need.

There are a number of things to note here.  The earlier stages are critical. If your analysis of the problem is not correct, you may build the wrong program!  The writing of the program is a small part of the overall process – some would say it is the trivial part.

7 IT Learning Centre PG002 Programming: Concepts for new programmers

 Some stages of the process are repeated many times, for example the build and test stages.  In some processes, the movement from one stage to another is very clear and well defined, in others it is less so.  For large programs, or large collections of programs, following a well defined process can be critical to the success of a project. A particular software process is often described using a diagram. The diagrams for two processes are included below, without explanation, simply to show that they can be quite different methods of working.

Figure 1 The ‘waterfall’ software development process

Figure 2 A ‘spiral’ software development process

IT Learning Centre 8 Programming: Concepts for new programmers PG002

3 What is a computer language? A computer language is the collection of words and symbols, and combinations of those words and symbols that can be used to describe a process that a computer should carry out. There are hundreds of different computer languages, some of which are tied to a particular computer, some of which are more generic. Many of these languages are related to each other. An indication of just how interrelated computer languages are is given in Figure 3 below (A more readable version is available at http://www.digibarn.com/collections/posters/tongues/) There are many more computer languages than are shown in the diagram, and you may wonder how you might go about choosing the best language to learn. The good news is that there are a lot of similarities between languages, and having learnt one programming language, it is often easier to learn another. Some brief advice on choosing a language is given in section 7.4.

9 IT Learning Centre PG002 Programming: Concepts for new programmers

Figure 3 A simplified hierarchy of some programming languages (From www.digibarn.com under a Creative Commons licence BY, ND, SA)

IT Learning Centre 10 Programming: Concepts for new programmers PG002

3.1. Computer language structure Every computer language has a set of reserved words, often called keywords, which have a particular meaning in the context of the language. Associated with these keywords there may also be a set of symbols, analogous to punctuation in a normal language, which can be combined with the keywords to further refine the meaning of the instructions. In most languages, a set of related keywords and symbols form a statement, or line, of your program. Here is an example of a statement from a program written in Java: double miles = kilometres * 0.621; double is a keyword, part of the Java language specification. The three symbols =, * and ; are also part of the language. miles and kilometres are data variables 0.621 is a constant. You might guess that this statement converts a distance in kilometres to the near equivalent in miles, although the exact meaning of double is probably not obvious. We will return to data variables and constants and what they are in a later section1. To return to our statement: just as in a normal language, order is important; ‘dog bites man’ has a completely different meaning to ‘man bites dog’. The placing of the symbols is also critical, and a computer is much fussier than a human at insisting that all the ‘punctuation’ is correct. The rules for which keywords are valid, in what order, and how the symbols are to be used is known as the syntax of the language. When you learn a new programming language, it is this syntax that is the most difficult to get to grips with. If you are using a text editor or simple word-processor to type in your program, it will be your responsibility to get the syntax correct. On the other hand, if you are using a program to create your own program, it will often give you a great deal of help with the syntax. Whichever way the program is written, there will be a stage where the syntax of your program is checked, and you will have to put right any syntactical errors. Once the syntax of your program is correct, a program is used to turn your list of instructions into a format that the computer can make use of; this format is much less human friendly and is sometimes called machine code. This conversion process is called either interpretation or compilation, depending on the language and programming tools being used, and is carried out by an interpreter or compiler program respectively.

3.2. Algorithms An algorithm is a sequence of steps that can be followed to solve a particular problem and so in a sense a computer program in its entirety is an algorithm. More commonly, an algorithm refers to that part of the computer program which implements the important behaviour of the program.

1 If you are familiar with algebra, variables and constants are placeholders for actual values, as in the equation y = mx + c, where numbers are substituted for letters when we want to work out the value of y.

11 IT Learning Centre PG002 Programming: Concepts for new programmers

For example, we might have a program which: Prompts the program user for a temperature in Fahrenheit Checks that the supplied information is a valid number Converts the temperature to Celsius Displays the answer to the program user Clearly the whole program is an algorithm; however the critical part of the program here is the conversion step. The algorithm for converting Fahrenheit to Celsius is: Subtract 32 and divide by 1.8 Why are we making the distinction? For common mathematical, statistical, engineering, financial and other calculations, an algorithm for a particular calculation will be well defined; we don’t have to reinvent it, we simply have to rewrite it using the syntax of the language. In Java, the temperature conversion algorithm might look like: double temperatureC = (temperatureF – 32) / 1.8; Clearly, if the program needs to carry out non-standard calculations or other processes you, as the , have to come up with the ‘algorithm’ to achieve it. Many programming languages have collections of algorithms that have been written and tested by other people and which you can use in your own programs. These collections are often referred to as libraries.

3.3. Pseudocode There may be some people who can think in a computer language such as C and Java, but they would be unusual (!) and this is certainly beyond the expectations of a beginner. When designing a program it can be a useful first step to write the program in a structured form of English that accurately describes the process, but avoids any particular programming language. This is often referred to as pseudocode. There is no standard form of pseudocode; you are free to write it in any way that helps you design your program. However, to be successful, pseudocode should:  Be easy to read  Be easy to understand  Be unambiguous  Describe what should be done NOT how it should be done  Avoid the use of a specific programming language syntax An example of pseudocode for a program to convert Fahrenheit to Celsius might look like this:

IT Learning Centre 12 Programming: Concepts for new programmers PG002

get a number from the program user check it is a number and more than or equal to -459.67 if it is not numeric or is less than -459.67 display a message to the user about the problem else subtract 32 divide by 1.8 display the answer on the screen Or if you prefer: get a number (TemperatureF) from the program user check TemperatureF is numeric and more than or equal to -459.67 if it is not numeric or is less than -459.67 display a message to the user about the problem else TemperatureC becomes (TemperatureF – 32) / 1.8 display the answer on the screen Or even: get TemperatureF if TemperatureF not numeric or TemperatureF less than -459.67 Error message else TemperatureC becomes (TemperatureF – 32) / 1.8 output TemperatureC Or any number of other equivalent blocks of pseudocode. Notice that the layout of the pseudocode is as important as the words used; by suitable use of indentation, we can make it clear which statements belong together. Once you are satisfied that your pseudocode correctly describes what needs to be done, you can use your knowledge of the chosen computer language to translate the pseudocode.

3.4. Pseudocode and comments Most computer languages allow you to include comments in the program. This is always good practice and many experienced programmers include the pseudocode as comments. Well written code is usually very readable to other programmers, to the point where the best code is often self-documenting. This means that the most useful comments are not describing how something is being done in the code, but the what – a much higher level of description. This is, of course, exactly what pseudocode is – the what and not the how. Comments are marked by special symbols so that they are usually ignored by the computer.

13 IT Learning Centre PG002 Programming: Concepts for new programmers

Exercise 4 An algorithm – Bubble sort There are many algorithms for sorting a list of numbers. This is one of the simplest (but least efficient)

Task 1 You will be given an envelope containing cards with numbers on them. Open the envelope. Remove the card with an arrow on it. Shuffle the remaining cards. Place the grid on a flat surface Task 2 Deal the cards randomly face up, arranged one above the other in one of the columns of the grid, like so (you will have different numbers):

Figure 4 Card arrangement for Exercise 4 Task 3 Put the arrow card next to the bottom most card, like so:

IT Learning Centre 14 Programming: Concepts for new programmers PG002

Task 4 Carry out the following steps: Pick up the number opposite the arrow Pick up the number above the empty space left behind Put down the bigger of the two numbers next to the arrow Put down the smaller of the two in the empty space Move the arrow up one number If the arrow is next to the top number, move it next to the bottom number Repeat the above steps Stop when no numbers are moved during a pass through them

Exercise 5 Creating your own algorithm – The Median In a similar way to the previous exercise, see if you can come up with your own algorithms in the following tasks.

Task 1 Use the same grid and numbers as for Exercise 4. Select any five of the numbers and randomly arrange them one above the other in the centre column on the grid. The MEDIAN of a group of numbers is the number midway between the lowest and the highest. In the space below, write an algorithm to identify the median of your group of five numbers.

15 IT Learning Centre PG002 Programming: Concepts for new programmers

Task 2 In the above tasks, did you need to introduce any concepts that we have not yet talked about?

IT Learning Centre 16 Programming: Concepts for new programmers PG002

4 Controlling how a program behaves Generally speaking we can consider our programs to be made up of a collection of lines, or statements. The order of the lines is important; it reflects the logical order in which a series of tasks needs to be carried out. Although each statement is normally carried out in the order in which it appears in the program, we can introduce extra flexibility if, in circumstances under our control, we allow some lines to be skipped and other lines to be repeated. There are three types of structure that allow us to control the order in which statements are carried out:  Sequence  Selection  Repetition

4.1. Sequence The sequence structure is the normal pattern in a computer program. Each statement in the program is executed with the subsequent statement not executing until the current one has completed2.

4.2. Selection In its simplest form, a selection structure involves a test being made to see whether a particular condition is true or false. If the outcome is true, one set of statements is executed, if it is false another set is executed. In pseudocode an example might be: if the door is open then switch on the red light sound the warning buzzer else switch on the green light Here the test is introduced by the If; we are testing to see if the door is open. The door is either open, in which case the outcome is true, or it is not open in which case the outcome is false. If the outcome is true, the indented statements between the then and the else are used. If the outcome is false, then the indented statements (here only one) after the else are used. It is important to realise that only one set of statements is used: the true set or the false set, never both. Notice the importance of indenting the pseudocode so that the selection structure is clear. If you prefer, you can add an extra line to demarcate the false block of statements:

2 Some program environments allow statements to be run in parallel, but we won’t concern ourselves with this in this module.

17 IT Learning Centre PG002 Programming: Concepts for new programmers

if the door is open then switch on the red light sound the warning buzzer else switch on the green light end if The end if is useful if you are working out the program using pencil and paper (on the back of an envelope?) when indentation can be more difficult to keep consistent.

4.2.1. Nested selection If necessary we can nest one selection structure inside another to model quite complex decision making. An example might be: if Number is less than 0 then sign is negative else if Number is 0 then no sign else sign is positive end if end if

4.2.2. Deeply nested selection Nesting selection structures to even a few levels can make it difficult to work out whether the logic is correct. if status is fulltime then holidays = 25 commission = 0 else if status is part-time then holidays = 13 commission = 0 else if status is contractor then holidays = 0 commission = 10% else if status = consultant then holidays = 0 commission = 20% else holidays = 0 commission = 0 end if end if end if end if A simple rewriting to avoid the large indenting can make the pseudocode more readable:

IT Learning Centre 18 Programming: Concepts for new programmers PG002

if fulltime then holidays = 25 commission = 0 else if part-time then holidays = 13 commission = 0 else if contractor then holidays = 0 commission = 10% else if consultant then holidays = 0 commission = 20% else holidays = 0 commission = 0 end if Remember, you are free to define your own way of writing pseudocode; what is important is clarity. In the example, notice the ‘catch all’ at the end of the pseudocode. Here it makes sure that if we have a person with a status that we have forgotten to include, holiday and commission at least get assigned a value (here of 0). Undefined values are a common cause of errors in programs.

4.3. Repetition Computers are tireless; they will repeat the same operation endlessly without getting bored or making a mistake. A repetition structure enables us to concisely describe how the same task should be repeated.

4.3.1. Pre-determined repetition If we know ahead of time how many times we want a task repeated, we can use what is commonly called a For Loop: loop for each employee increase salary by 5% end loop Or, if we know that we need to repeat an operation a constant number of times: for 3 times sound buzzer end for Or, in a more code-like pseudocode: n = 3 for i = 1 to n sound buzzer next i In all cases, once the required number of repetitions has been carried out, the program continues with any statements that follow the repetition structure.

4.3.2. Conditional repetition Sometimes we will not know how many times a set of tasks needs to be repeated, but we will know when to stop, typically when a particular condition is met. In a similar way to making a test to see which selection of tasks we should carry out

19 IT Learning Centre PG002 Programming: Concepts for new programmers

(See section 4.2), we can make a test to see if we should carry on with a repeated action. There are two places we can make this test: at the beginning of the loop or at the end, often referred to as pre-test and post-test loops. In a pre-test loop, we make the condition test the first statement in our loop: loop while bucket is not full add beaker of water end loop An important aspect of the pre-test loop is that the tasks MAY NEVER GET CARRIED OUT. In our example: if the bucket is already full then the condition is already satisfied and so the enclosed statements are skipped. In a post-test loop, we make the condition test the last statement in our loop: loop add beaker of water end loop when bucket is full Here, the tasks WILL ALWAYS BE CARRIED OUT AT LEAST ONCE. In our example, we don’t check if the bucket is full until we have been through the loop once. In both cases, as soon as the computer can verify that the condition has been met, the looping stops and the program continues with the statements that follow the repetition structure.

IT Learning Centre 20 Programming: Concepts for new programmers PG002

Exercise 6 Efficient use of control structures There are many ways to write a program; some are more efficient than others. Efficiency can be measured in terms of how quickly the program runs, how much memory it takes up (the program size) or, most important to us her,e how easy it is to understand. Task 1 Work through the pseudocode below to discover what it is doing

write the numbers 0 to 5 move down a line write the number 1 write the numbers 1 to 5 multiplied by 1 move down a line write the number 2 write the numbers 1 to 5 multiplied by 2 move down a line write the number 3 write the numbers 1 to 5 multiplied by 3 move down a line write the number 4 write the numbers 1 to 5 multiplied by 4 move down a line write the number 5 write the numbers 1 to 5 multiplied by 5

21 IT Learning Centre PG002 Programming: Concepts for new programmers

Task 2 Rearrange the following lines to create pseudocode that achieves the same result as the code above. end for for five times increase m by 1 move down one line write the numbers 0 to 5 set m to 1 write the numbers 1 to 5 multiplied by m write the value of m

Task 3 The program above currently works for the numbers 0 to 5. How would you change it to work with the numbers 0 to 12?

How would you extend the program so that it would work for any upper limit supplied by the user when the program is run?

IT Learning Centre 22 Programming: Concepts for new programmers PG002

5 Data So far we have focused on tasks and actions that programs carry out. However, programs mean little without data, and how that data is structured is critical to the fundamental nature of programming. Programs are often considered to have three stages: Input, Processing and Output. This implies that a program is only a process that converts one thing into another. Clearly most useful programs are more than this, but the process view is useful, and emphasises the importance of data. Data can be any information that we want our program to take account of and manipulate. It could be text, numbers, images, sounds (even program code!). At the lowest level in a computer all data is represented as a collection of 1s and 0s, but usually this structure, and how it comes to represent the text, numbers and other data that we want to use, is hidden from us. A good understanding of the binary system and how this is used in computers can be useful background (even essential in some areas of programming) and there are many textbooks and web-based resources that cover this. Unfortunately (or fortunately, depending on your viewpoint!) we don’t have time to cover it here and it is not critical to the concepts we are discussing.

5.1. What is a variable? Data has to be held somewhere in the computer so that it is available to our programs. Recall that programs are held in the computer memory (most usually in Random Access Memory, RAM). This is also a suitable place to store our data. The way that data is held in memory has to be carefully controlled. As we discussed above, data is just a collection of 1s and 0s and so we need a system which ensures we know which collections of 1s and 0s relate to which data. A variable is an area of memory that holds an item of data (strictly speaking it could be a collection of related data). For our convenience, each variable has a unique name that we can use to refer to the data. Usually we are free to choose the name for a variable, although each programming language will have its own rules governing the choice of variable names. It makes sense to choose a name that reflects what the data is. Good variable names might be: FirstName DateOfBirth AccountNumber xValue Poor variable names might be: ABC gndlf It can help to visualise a variable as a container of a particular size, with a label on it being the variable name. A computer language will have a way in which we can put a value in this container. This operation is called assignment, and is usually represented by a symbol such as = or a combination of symbols such as := We are concerned here only with pseudocode, and in our pseudocode it is best to keep things simple, so typically the = symbol is used. Returning to a variation in a previous example:

23 IT Learning Centre PG002 Programming: Concepts for new programmers

TemperatureF = value from user if TemperatureF not numeric or TemperatureF < -459.67 Error message else TemperatureC = (TemperatureF – 32) / 1.8 output TemperatureC end if Here we are using two variables, TemperatureF and TemperatureC. In the first line, TemperatureF on the left of the = is assigned a value from the user (perhaps they type it in) on the right of the =. A few lines later we assign the variable TemperatureC the result of taking whatever value is in TemperatureF and performing some simple calculations on it. Notice the order: what is on the left of the = is assigned the value on the right. The action of looking at a variable to see what value it holds and then using that value in a calculation does not change the variable. If we want to change the value of a variable, perhaps add something to it: TemperatureC = TemperatureC + 1 This says ‘take a look at what is in TemperatureC, add 1 to it, and then replace what is in TemperatureC with the new value’

5.2. What is a constant? We saw in the above example that we can change the value held in a variable, hence the origin of the term. Sometimes we want a fixed value in our program, one that can be guaranteed not to change. Most computer languages allow you to have a container (memory location) that once filled, can never be changed. These containers are called constants, and like variables they can have names. How constants are differentiated from variables is a language specific, but in pseudocode a good convention is to use UPPERCASE to identify a constant. Let’s look at our example again: TemperatureF = value from user if TemperatureF not numeric or TemperatureF < -459.67 Error message else TemperatureC = (TemperatureF – 32) / 1.8 output TemperatureC end if In the third line there is a curious number: -459.67. It is in fact the value of absolute zero (the lowest temperature possible) in Fahrenheit. It would be good practice to make this clearer in our pseudocode:

IT Learning Centre 24 Programming: Concepts for new programmers PG002

ABSOLUTE_ZERO = -459.67 TemperatureF = value from user if TemperatureF not numeric or TemperatureF < ABSOLUTE_ZERO Error message else TemperatureC = (TemperatureF – 32) / 1.8 output TemperatureC end if Here we assign the constant a value in the first line. We can then use the value contained in the constant later in the program ((line 4). If would be an error in a program to try and change the value of a constant once it has been initially assigned; it is usually better to get an error in our program than it would be to allow the constant to be changed (and here change the laws of physics!). Most programming environments will detect that you are trying to change a constant early in the design process and so prevent the error ever occurring by pointing it out to you.

5.3. The types of data Earlier we said that a good mental model of a variable is a container with a label on it. In principle we could define this container to be large enough to hold any type of data, whether it is a small number, a date, or someone’s address, or someone’s picture. However, this would be inefficient and wasteful of the limited memory a computer has available. For efficiency, variables are created with a specific size, able to hold a particular type of data. So for a small number, we would use a small container, for a picture we would use a large container. Some programming languages do not need to be told what type of data you are using, they can work it out for themselves. So if we had pseudocode: TemperatureF = 23 myAddress = 13 Banbury Road we would not need to concern ourselves with making sure that TemperatureF was of a size to hold an integer number, and myAddress able to hold 15 characters; the programming language would work it out (and usually get it right!). Most languages however, require you to specify the size of any variable you want to use. In our discussion this is not too critical, since we are using pseudocode to give us an overview of the programming process, but as a taster, the table below shows some of the different types of data available in the Visual Basic programming language.

25 IT Learning Centre PG002 Programming: Concepts for new programmers

Data Value range Used for Memory Type used (Bytes) Boolean 0 or 1 True or False 1 Byte 0 to 255 Small integer numbers 1 Currency -922,337,203,685,477.5808 to Currency or other values which 8 922,337,203,685,477.5807 need handling to high accuracy Date January 1, 100 to Any date or time 8 December 31, 9999 Double -1.79769313486232E308 to Large numbers to 14 digits of 8 -4.94065645841247E-324 for accuracy negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Integer -32,768 to 32,767 Integers in the given range 2 Long -2,147,483,648 to 2,147,483,647 Large integers 4 Single -3.402823E38 to -1.401298E-45 Large numbers to 6 digits of 4 for negative values; accuracy 1.401298E-45 to 3.402823E38 for positive values. String A variable-length string can Text 10 +1 for contain up to approximately 2 each billion (2^31) characters. character A fixed-length string can contain up to approximately 64K (2^16) characters. Variant Encompasses the full range of Any type of data Numbers: values for the other data types 16 bytes Characters: 22 + 1 for each character

IT Learning Centre 26 Programming: Concepts for new programmers PG002

Exercise 7 Identifying data types Most languages use a very similar classification of data to that given in the table above (although some of the detail, such as memory usage would be different) Task 1 Using the table of data types given above as a guide, identify the best data type to represent the following data

To record I would use this data type Person’s surname Person’s date of birth Whether a person is a shift worker or not Company profit Floor number in a skyscraper Person’s age Population count for a city Area of the Earth’s surface in m2 Students’ average height Postcode Telephone number Distance between two towns in UK

Task 2 Some of the above data have a particular type of unit implied: for example, the distance between towns in the UK is most likely measured in miles. How do you think units might be represented in a program?

5.4. Operators We need to mention here the operations that can be carried out on data. You will probably be familiar with the common operators in mathematics and algebra: + Addition - Subtraction * Multiplication / Division In the majority of programming languages these same symbols are used to represent the same operations. So to add one variable to another and assign the result to another variable we might see:

27 IT Learning Centre PG002 Programming: Concepts for new programmers

population = urbanPopulation + ruralPopulation Note the use of another operator, assignment, here denoted by =. Other operations are represented by symbols that are defined for particular languages. For example in Java the % symbol is used to represent the remainder operator: 7 % 3 would give the result 1 When you start to learn a programming language, you will need to pay particular attention to the operators that are used – they can lead to confusion. For example, in Visual Basic, the assignment operator is =, but the = symbol is also used to compare two values. However, in C++ the = symbol is again used as assignment, but comparison operations use the double equals ==.

5.5. Data structures Variables and constants are widely used; it would be difficult to write a program without using them. However, some data has structure that does not fit well with a single piece of information being stored. For example, a person’s address can be viewed as a collection of information: house number, street name, town, postcode, each of which we may want to handle separately. There is also the issue of storing information about several similar items. For example, a collection of temperature measurements made at different times; we would like to be able to identify each one independently, but it would be tedious to create a separate variable (with a sensible name) for each one. Programming languages have a number of solutions for handling structured data and, although similar in principle between languages, there are variations in detail. If you choose to learn a computing language, these structures will be covered in detail. We will touch on two structures here: arrays and lists.

5.5.1. Arrays Arrays are featured in most computer languages and in its simplest form an array is a collection of variables, all with the same name, but uniquely identified by an index number. In the same way as imagining that a variable is a labelled container, it is useful to think of an array as a set of pigeonholes, with each slot identified by a number. If we want to place information in a particular slot we need to give both the name and index number: Temperature(0) = 15.5 Temperature(1) = 15.7 Temperature(2) = 16.0 Notice that, as often happens in computing, we start counting from 0 rather than 1. Arrays are well suited to being used with a repetition structure (section 4.3):

IT Learning Centre 28 Programming: Concepts for new programmers PG002

for n from 0 to 2 Temperature(n) = value typed by user end for

for n from 0 to 2 Display Temperature(n) end for In the example above, the Temperature array is one-dimensional. In most languages, it is possible to define arrays that have two or more dimensions. Figure 5 illustrates how we might imagine a one-dimensional and a two dimensional array to be set up.

Figure 5 A model of one- and two-dimensional arrays

Exercise 8 Using a data structure (arrays) Data structures such as arrays and repetition structures are a powerful and very common programming combination.

You might find the following grid useful in this exercise:

Note that in computing we generally start counting from 0 rather than 1.

Also, in this ‘language’, cells are identified by column first and then row.

29 IT Learning Centre PG002 Programming: Concepts for new programmers

Task 1 ‘Execute’ the following program by working through it.

RowNumber = 0 ColumnNumber = 0

loop while RowNumber <= 3 loop while ColumnNumber <= 3 GameBoard(ColumnNumber,RowNumber) = blank ColumnNumber = ColumnNumber + 1 end loop

ColumnNumber=0 RowNumber = RowNumber + 1

end loop

RowNumber = 0 ColumnNumber = 0

loop while RowNumber <= 3 loop while ColumnNumber <= 3 if ColumnNumber is odd and RowNumber is odd then GameBoard(ColumnNumber, RowNumber) = red end if

if ColumnNumber is even and RowNumber is even then GameBoard(ColumnNumber, RowNumber) = blue end if

ColumnNumber = ColumnNumber + 1

end loop

ColumnNumber = 0 RowNumber = RowNumber + 1

end loop

ColumnNumber = random whole number between 0 and 3 RowNumber = random whole number between 0 and 3

GameBoard(ColumnNumber, RowNumber) = yellow

5.5.2. Lists A list, more accurately called a linked list, is a collection of data where each data item is linked to the next item in the list. There is therefore an implied order in the list which we can use in whatever way is appropriate; for example we could have a linked list of names that we have ordered alphabetically.

IT Learning Centre 30 Programming: Concepts for new programmers PG002

We can visualise a simple linked list as a collection of items (often referred to as nodes) where one of the elements of an item points to (or is a link to) the next item in the list:

In a simple linked list the last node is empty to signify the end of the list. We could link the last item back to the first to create a circular list:

One of the disadvantages of a simple (or circular) list is that we can only navigate the list one way. To overcome this, although at the expense of requiring extra memory, is to have a doubly linked list where each node contains a forwards and a backwards link:

The advantage of a list over an array is that we can easily insert, remove or re- order a list member without having to reorganise the entire data structure. To insert a new item in the list:

And to re-order a list is simply a matter of changing the appropriate links:

31 IT Learning Centre PG002 Programming: Concepts for new programmers

6 The ‘shape’ of programs Many programs run to several hundred lines of code. Collectively, a complex program like Windows Vista or Mac OSX will have millions of lines of instructions. This presents three significant problems:  Someone, probably some many, will have to write all of those lines  The lines of program have to be accessible and understandable not only to the original programmers, but also to programmers who may become involved in the project later  It must be possible to maintain the program in a way that reduces the risk of fixing one error only to introduce one (or more!) other errors. One of the most powerful features of any computer language is the ability to collect together a number of statements and make them available for use throughout the program. A collection of such statements is called a function (or procedure, or subroutine depending on the language) and usually given a name so that it can easily be referenced.

6.1. Functions The diagram in Figure 6 shows the advantage of collecting common code into a function. The column on the left represents many lines of code. The white areas are blocks of code which are repeated; they carry out the same steps in different parts of the program. In the right-hand column, the common code has been collected into a function (the white block on the far right). When the program needs to carry out those steps, it jumps to the function, carries out the steps and then jumps back to the next statement in the program.

Figure 6 Collecting common code in a function

The advantages of this are as follows:

IT Learning Centre 32 Programming: Concepts for new programmers PG002

Efficiency We only need to write the statements in the function once. They can then be reused wherever they are needed. This makes our programs shorter and quicker to write. Readability The program is easier to understand. To see why this is so, let’s see how we might use a function in pseudocode. Here is a part of a program: … obtain a Celsius temperature TemperatureC TemperatureF = TemperatureC * 1.8 TemperatureF = TemperatureF + 32 display TemperatureF …

Using a function, this might look like … obtain a Celsius temperature TemperatureC convert TemperatureC to TemperatureF in Fahrenheit display TemperatureF …

In the first example, when we are reading through the code, we have to stop and think what the calculation is doing (or read any associated comments), in the second example, we can immediately see what is happening (a temperature conversion), but don’t need to concern ourselves about the detail. If we do need the detail, we go to the function and read through that. Just so that you get a feel for how this might work, here is the example written in a more code-like pseudocode: TemperatureC = input from user TemperatureF = ConvertCtoF(TemperatureC) output TemperatureF Here the function is called ConvertCtoF and is given the variable TemperatureC to use. The value that ConvertCtoF produces is placed in the variable TemperatureF for use later on. If we were to look at the corresponding pseudocode for ConvertCtoF we might have: Function ConvertCtoF (SuppliedTemperature) return (SuppliedTemperature * 1.8) + 32

Of course, how functions are actually implemented is language specific. Maintainability Collecting common code statements into a named function makes it easier to maintain the program. Imagine that we make a mistake in the way we convert Celsius to Fahrenheit – perhaps we multiply by 2 instead of 1.8. When we spot the error during our testing, we only have to make the change in one place, the function that does the conversion, and not in many different places throughout the program.

33 IT Learning Centre PG002 Programming: Concepts for new programmers

6.1.1. Argument (or Parameter) passing We can extend the usefulness of functions even further by enabling them to be supplied with values to be used during the function. These are usually called arguments or parameters (depending on the language and/or personal preference of the programmer). The exact details of how these arguments are treated depend on the computer language. In its simplest form, an argument is a value that we hand on to the function, but which cannot be changed. Some languages enable variables (or whole data structures) to be passed to a function and changed as required so that they potentially have new values on completion of the function. A common behaviour of functions is to have a return value, which is something that is sent back to the calling program. Often this is a simple True or False to indicate success or failure of the function, but it could be an error code, or a value that the program then takes and stores in a variable for later use.

6.1.2. Re-use of code One of the advantages of functions is that they can be re-used in different programs. In fact, many programming languages provide libraries of functions that you can make use of in your own programs. When you write your own functions, it is always worth considering whether, with a small amount of thought, you could make them generic enough that you open up the possibility of re-using them in future programs that you might write, or even making them available to other programmers. Functions, and indeed programs, are classed as intellectual works in the same way as the creation of a paper, novel, image or work of art, and the same principles of intellectual property, e.g. copyright, apply. Copyright is a complex issue. Libraries of functions that are supplied as part of a programming environment, or that you purchase commercially, will have conditions of use attached to them and you should take care that you abide by those conditions. This is particularly important where you anticipate distributing your code either for free or commercially. Due to the complexity of copyright, you should seek informed advice if you are in doubt. Your departmental librarian may be able to point you in the direction of a suitable person. If you develop a program that you think has commercial potential, then you can also get advice from Oxford University Innovation, a wholly owned subsidiary of the University, who can advise University members on technology transfer (http://innovation.ox.ac.uk/).

IT Learning Centre 34 Programming: Concepts for new programmers PG002

Exercise 9 Using functions Functions (or the equivalent in any particular computer language) are fundamental to good programming practice. Wherever you find yourself writing similar code to what has already been written you should consider using a function. Task 1 Execute the following pseudocode. It is written as a main program (CardDeck) that uses two functions (Fold and Divide)

program CardDeck take a sheet of A4 paper Fold(“Short edge”) Divide()

for each sheet of paper Fold(“Long edge”) Divide() end For

loop twice for each sheet of paper Fold(“Short edge”) Divide() end for end loop end program

function Fold(edge) fold in half parallel to edge crease firmly end function

function Divide() if no fold do nothing else unfold tear along crease end if end function

Task 2 You upgrade the program to make use of scissors (!). What do you need to change?

Where was parameter passing involved?

35 IT Learning Centre PG002 Programming: Concepts for new programmers

6.2. Objects When we are analysing a problem that we hope to solve using a computer program, we will often find that we are considering real world objects and their behaviour. For example, if we were writing a program to control road traffic through the use of traffic lights and warning signs, we might be considering the following objects: Vehicles Cars Lorries Motorcycles Bicycles Pedestrians Roads Traffic lights Signs Information signs Warning signs Each of these objects has some behaviour. For example: Vehicles can: Start Stop Travel Turn And objects also have properties. For example: Vehicles have: Speed Direction Length A certain number of wheels And we ought to mention that objects can contain other objects; a vehicle will contain an engine, although how deeply we follow that logic depends on the model that we are building. To create a program that correctly models the behaviour of traffic, we might like to represent these objects, their behaviour and their properties in our code. Any computer language will allow you to write code to model this traffic system. For example we could use variables to keep track of the properties of objects and we could use functions to help represent their behaviour. However, some computer languages lend themselves more easily to modelling real-world objects. These languages are usually referred to as object-oriented and include C++ and Java. In an object-oriented computer language, there are features that allow you to create an object in much the same way as we might create a variable. The difference is that an object contains both data (usually in the form of its own variables) and behaviour (usually in the form of its own functions).

IT Learning Centre 36 Programming: Concepts for new programmers PG002

6.2.1. Encapsulation: Data and Behaviour Objects are said to encapsulate their properties and their behaviour. In simple terms this means that we can think of an object as a self-contained item, the inner workings of which are hidden. In order to interact with an object, for example to find out the value of one of its data properties, you ‘ask’ it to supply the information to you. Let’s consider an example in the real world. If we want to know someone’s date of birth we ask them. How that is remembered (stored) by the person is hidden from us, and we don’t really care, as long as we get the answer. Similarly, if we want to know the person’s age, we ask them. Internally, they calculate their age, or remember the number on their last birthday card, or make it up; the important thing is we don’t know. More importantly, if the person decides to calculate their age in a different way next time you ask, we wouldn’t know, and may not care. Objects in a computer program behave in a similar way. Once written and made available to the program, how they store their data and perform their actions is hidden from us so that we cannot accidentally change them, or use them in an inappropriate way. This is a very powerful way of writing robust, maintainable programs and is becoming a popular paradigm for software development, although it is by no means universally accepted as the best way!

37 IT Learning Centre PG002 Programming: Concepts for new programmers

7 What next? The IT Learning Centre runs a number of courses that cover specific programming languages. You can find details at courses.it.ox.ac.

7.1. A hands on introduction using Alice If you would like to experience some of the concepts covered in this module in a more practical way, you may like to download the Alice programming environment. Alice is

“… an innovative 3D programming environment that makes it easy to create an animation for telling a story, playing an interactive game, or a video to share on the web. Alice is a freely available teaching tool designed to be a student's first exposure to object- oriented programming. It allows students to learn fundamental programming concepts in the context of creating animated movies and simple video games. In Alice, 3-D objects (e.g., people, animals, and vehicles) populate a virtual world and students create a program to animate the objects.” from www.alice.org (11th April 2011) Alice is available for Windows and Mac OSX and can be downloaded freely from the Alice web site at www.alice.org. Note: Alice is purely a teaching environment – you will not find it suitable for creating programs useful in your work or research; however it is an excellent introduction to the concepts involved.

7.2. Playing with SCRATCH For a more visual introduction to programming you should try SCRATCH. SCRATCH is a web-based environment for learning programming. Although it is designed with young people in mind, it demonstrates all the key features of a programming language using point-and-click and drag-and-drop. SCRATCH works in most browsers and can be found at scratch.mit.edu.

7.3. An example of a Java program Overleaf is a complete example of a Java program. You may like to work your way through the code and see how much of it you can understand. The example is well commented and the variables, objects and methods (similar to functions) have been given good names. You will not understand all of the program (you need a Java course for that!), but hopefully it will give you some encouragement that programming is not difficult. The example is taken from an early edition of the book Java in a Nutshell by David Flanagan. A working example can be found at http://oreilly.com/catalog/javanut/examples/

IT Learning Centre 38 Programming: Concepts for new programmers PG002

// This example is from the book _Java in a Nutshell_ by David Flanagan. // Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates. // You may study, use, modify, and distribute this example for any purpose. // This example is provided WITHOUT WARRANTY either expressed or implied. import java.applet.*; import java.awt.*; public class Scribble extends Applet { private int last_x = 0; private int last_y = 0; private Color current_color = Color.black; private Button clear_button; private Choice color_choices;

// Called to initialize the applet. public void init() { // Set the background color this.setBackground(Color.white);

// Create a button and add it to the applet. // Also, set the button's colors clear_button = new Button("Clear"); clear_button.setForeground(Color.black); clear_button.setBackground(Color.lightGray); this.add(clear_button);

// Create a menu of colors and add it to the applet. // Also set the menus's colors and add a label. color_choices = new Choice(); color_choices.addItem("black"); color_choices.addItem("red"); color_choices.addItem("yellow"); color_choices.addItem("green"); color_choices.setForeground(Color.black); color_choices.setBackground(Color.lightGray); this.add(new Label("Color: ")); this.add(color_choices); }

// Called when the user clicks the mouse to start a scribble public boolean mouseDown(Event e, int x, int y) { last_x = x; last_y = y; return true; }

// Called when the user scribbles with the mouse button down public boolean mouseDrag(Event e, int x, int y) { Graphics g = this.getGraphics(); g.setColor(current_color); g.drawLine(last_x, last_y, x, y); last_x = x; last_y = y; return true; }

// Called when the user clicks the button or chooses a color public boolean action(Event event, Object arg) { // If the Clear button was clicked on, handle it. if (event.target == clear_button) { Graphics g = this.getGraphics(); Rectangle r = this.bounds(); g.setColor(this.getBackground()); g.fillRect(r.x, r.y, r.width, r.height); return true; } // Otherwise if a color was chosen, handle that else if (event.target == color_choices) { String colorname = (String) arg; if (arg.equals("black")) current_color = Color.black; else if (arg.equals("red")) current_color = Color.red; else if (arg.equals("yellow")) current_color = Color.yellow;

39 IT Learning Centre PG002 Programming: Concepts for new programmers

else if (arg.equals("green")) current_color = Color.green; return true; } // Otherwise, let the superclass handle it. else return super.action(event, arg); }

}

IT Learning Centre 40 Programming: Concepts for new programmers PG002

7.4. Choosing a computer language to learn Each language has its strengths and most languages can be used for most tasks with varying degrees of ease and efficiency. Also, it would not be unusual to use more than one computer language on a project (mixed-language programming). Choosing a particular language to learn depends on a number of factors: Learning resources available: You will not be able to find a taught course for every language. In the IT Learning Centre we offer six or so different computer language courses. You may have access to other learning resources, such as books and computer-based tutorials, for a particular language in your college or department. Existing projects: You may be hoping to carry on an existing project started by someone else, or join a team that already uses a particular language. Popularity: There are fashions in computer languages as with most other things. A language that is currently popular may have more learning resources immediately available. Job market: If you are learning a computer language to improve your employment prospects, you should look in various trade journals and computer publications to see what skills are being sought. Availability of a mentor: It can be very useful to know someone who is familiar with your chosen language, to whom you could talk when you hit a problem. Cost: Some computer languages and the associated development tools are open source and free, others are proprietary and have to be purchased. Some development environments can be expensive for an individual to buy, although there are often academic discounts available. It is clearly not possible to recommend here which language would be best suited for your tasks; however, below is a very brief description of a few popular languages. Typically, when someone is writing in a computer language for the first time, they create a very simple program as a trial run. This is often a program that displays “Hello World” on the screen. An example of a Hello World program is given for each language so that you can see what the code looks like.

7.5. C The oldest language discussed here, C first appeared in 1972, having been developed for 10 years by Dennis Ritchie at Bell Labs. Initially it was closely linked with the UNIX operating system, but has grown into a hugely influential general purpose language available for virtually all computer systems and is one of the most widely used programming languages today. There are a number of different implementations. Most of these try to comply with the ANSI C standard, but with mixed success! An advantage of the standard is that a carefully written C program for one type of computer can be ‘ported’ to run on another type. C has a minimal set of features and was designed to enable low-level access to computer memory and hardware as well as being suitable for creating user level applications. The compactness of the C language makes it relatively easy to learn, however its minimal feature list means that the programmer is left to handle many of the operations (such as memory management) that other languages do automatically. On the plus side, C programs can be made very fast and efficient in terms of

41 IT Learning Centre PG002 Programming: Concepts for new programmers

memory usage. Most operating systems are written in C, Android being a recent example. There are a number of open source and freeware implementations of C that can be downloaded from the web. #include

int main(void) { printf ("Hello, world!\n"); return 0; }

7.6. C++ C++ is a derivation of C created in 1983 by a Danish computer scientist called Bjarne Stroustrup. It is designed to add object-oriented functionality to the language – “C with classes”. It is essentially a superset of the C language; many C programs can be recompiled in a C++ environment. The language is very stable and major updates are rare, the most recent arriving in 2014. C++ has declined in popularity in recent years, possibly because it is not widely used for mobile systems, but it is still in the top tier of modern programming languages. The extra features, not least object-orientation, introduced in C++ necessarily make the language somewhat complex, and it is generally regarded as a more difficult language to learn and to use effectively. Compilation can be slow and memory usage can also be inefficient. Various newer languages such as Go (Google), Rust (Mozilla) and D (used at Facebook) try to improve on this. Nevertheless, the advantages offered by the object-oriented paradigm of C++ can be worth the extra effort involved in becoming skilled in the language and the complexity is to some extent compensated for by the C++ Standard Template Library (STL) which provides access to commonly used programming structures and algorithms. Just as with C, C++ has low-level access to the computer but at the same time can be used to write standard applications. There are a number of open source and freeware implementations of C++ that can be downloaded from the web. #include

int main(void) { std::cout << "Hello, world!\n"; return(0); }

7.7. Java Originally developed in the mid-nineties at Sun for interactive television services, Java is now arguably the world’s most popular language with approximately 9 million programmers using it for web applications. Java is currently owned by Oracle, “the steward of Java technology”. The language is designed to be inherently cross-platform – Write Once, Run Anywhere (WORA). It is quite usual, for example, that a Java program written for a PC will run unaltered on a Mac. Variations of the Java development environment are available for most computers.

IT Learning Centre 42 Programming: Concepts for new programmers PG002

Java, like C++, is object-oriented. Although this is open to debate, it is often said that for newcomers to object-oriented programming Java is easier to learn. Many of the structures and behaviour (such as memory management), that C++ programmers need to think carefully about, are handled automatically in Java. Programs written in earlier versions gained a reputation for being slow as Java is not as tightly integrated with machine instructions as languages like C, but in modern environments any lag is typically barely noticeable. Java for Windows, Mac, Linux and Solaris can be downloaded for free from: https://www.java.com/en/download/help/download_options.xml

class HelloWorld {

public static void main (String args[]) { System.out.print("Hello, world!"); } }

7.8. JavaScript JavaScript is used a lot in game design and development for mobiles and can also be written directly into web pages to provide automation. Originally developed at Netscape and called LiveScript, the name was changed when Netscape did a deal with Sun in the nineties to use their popular, new Java language. Unlike Java, it is a true “script” language in that it is not compiled. Its widespread adoption by “amateur” web authors has alienated some professional developers, but it still regularly rivals Java for the title of world’s most popular programming language. The language, similar in some ways to C, is simple to learn and relies on its host environment for input and output facilities such as printing, storage and graphics which makes it very adaptable, but differences in what browsers and devices support can lead to compatibility issues. When used with web pages it is essential to gain a good understanding of the Document Object Model (DOM) that underlies the handling of web pages by web browsers. JavaScript is supported natively by all major browsers, but sometimes needs to be enabled before it is available. Hello World in JavaScript

7.9. MatLab MatLab is a numerical analysis package that also includes a programming language. The MatLab package is available for a number of different computer systems, including Windows, Mac and Linux, however the programs written in the MatLab language are generally only ‘runnable’ on a computer with a version of MatLab installed (there are ways around this). The language itself is optimised for mathematical operations, especially those involving matrices, and can be very fast and efficient at solving complex

43 IT Learning Centre PG002 Programming: Concepts for new programmers

mathematical problems. The language is compact and no more difficult to learn than any other, but clearly some mathematical understanding is needed to make full use of its features. Matlab is a commercial package available from the MathWorks company. There are special academic and student licence deals available. disp("Hello World ")

7.10. Perl Designed in 1987 by Larry Wall as a script language for UNIX to facilitate reporting, Perl became widely adopted for web site programming and more recently its usage has expanded to many other areas such as networks and finance. In contrast to some other languages, Perl encourages the philosophy of multiple ways to achieve something. Powerful and flexible, if somewhat inelegant, Perl is particularly suited to manipulating text and handling text files and is often used as a ‘glue’ language with which to stick together other programs so that they can interact with each other. These abilities have led to its reputation as “the Swiss Army chainsaw of scripting languages,” and “the duct tape that holds the internet together”. Perl 5 was released in 1994 and was followed a year later by the creation of CPAN (Comprehensive Perl Archive Network), the major repository of resources for Perl and related modules. In July 2002 Perl 5.8 was released, which is still the most popular version of Perl. Perl 6, an attempt to redesign the language without backwards compatibility, finally reached version 1.0 at Christmas 2015 having been in development since 2000. Perl is relatively uncomplicated in terms of its syntax and is comparatively easy to learn and use, but is gradually being overtaken in popularity by Python which can now match its long-held CPAN advantage. Perl can be downloaded freely for most operating systems. print "Hello, World!\n"

7.11. PHP PHP was originally some utilities written in C by Rasmus Lerdorf to maintain his Personal Home Page and manage web forms and databases - “I don’t know how to stop it. There was never any intent to write a programming language.” Others took it up and gradually Zend Technologies’ versions of PHP became the market leader. PHP is open source, so development depends on the enthusiasm and effort of the PHP community which can lead to gaps in support and setbacks like the abandonment of PHP6 where the community lost interest in rewriting PHP to support Unicode: http://www.slideshare.net/andreizm/the-good-the-bad-and-the-ugly-what- happened-to-unicode-and-php-6 PHP is mainly used on web servers to provide dynamic web sites by creating web pages ‘on the fly’ when requested by a user through a browser. To do this, PHP often interacts with a database that holds the information being requested. Usually PHP code is embedded within an HTML document (web page). The PHP environment takes the HTML and interacts with it based on these embedded instructions.

IT Learning Centre 44 Programming: Concepts for new programmers PG002

PHP is included with virtually all Linux distributions and can be downloaded freely from the web for other platforms,

7.12. Python Python (named after Monty!) was originally developed by Guido van Rossum, now considered Python’s BDFL (Benevolent Dictator For Life). It was designed as a small core language with a large standard library and lots of scope for 3rd party extensions. As the origin of the name suggests, irreverence is a key principle in the thriving Python community. Readability and simplicity are also a priority. Unlike some of its competitors there is a strong convention that “there should be one—and preferably only one—obvious way to do it”. It is an increasingly popular language especially for text processing, but also for many other applications. It is fully object-oriented and is regarded of one of the easier languages to learn. CPython is the modern reference implementation. Code can be packaged into standalone executables if an interpreter is not available for a platform. There are versions for Windows, Mac and Linux. print "Hello, World!"

7.13. C# Released in 2000 by Microsoft as a “C-like Object Oriented Language” for use with its new .NET Framework. Microsoft presented it as their take on C++, but Sun developers called it an imitation of Java. “#” might be considered a musical ‘plus’ and happens to contain four “+” symbols. C# has steadily outgrown its sister language, VB.NET, and is now recognised as one of the top 5 most popular programming languages. It may also become the .NET developers tool of choice for mobile work. The reference compiler is the open source Microsoft Visual C#, but others are available. A C# compiler could generate machine code, though typically they generate code that’s at least partially human readable. using System;

class Program { static void Main(String[] args) { Console.WriteLine("Hello, world!"); } }

45 IT Learning Centre PG002 Programming: Concepts for new programmers

7.14. Objective-C In the early 1980s telecom engineering developers Brad Cox and Tom Love tried to extend C to make interchangeable software components, incorporating elements of the language. Objective-C was licensed by NeXT in 1988 and used in their NeXTSTEP (and later OpenStep) platform for custom programming. When Apple bought NeXT in 1996 they incorporated OpenStep into the Mac OS X. #import

int main (int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSLog (@"Hello, World!"); [pool drain]; return 0; }

7.15. Swift Developed by Apple (with Chris Lattner in the lead), but now open source, the idea behind Swift, released in 2014, was to make a modern, safer and more robust alternative to Objective-C, avoiding problems like the “Pyramid of Doom” which typically causes a crash. Described sometimes as “Objective-C without the C” it borrows ideas from lots of modern languages. Apple is driving it as the successor to Objective-C, but it is also available for Linux and other platforms are considering it. print ("Hello, World!")

7.16. Visual Basic Visual Basic (VB) was released by Microsoft in the 1990s as one of several programming tools for its Component Object Model (COM) declared legacy in 2008. Its strong visual element and generous supply of building block “objects” made it appealing to many new programmers who had worked with BASIC at school or college and made it almost a surprise success as a tool to develop the new graphical user interface (GUI) applications The final release was version 6 in 1998 and Microsoft stopped supporting it ten years later, but VB’s enduring popularity meant that in recent years some developers made public calls for a new version. The Visual Basic for Applications (VBA) variant of the language is still used as a ‘macro’ or scripting language within several Microsoft applications, notably Microsoft Office, which means it is still widely used and often provides an accessible way into programming even for today’s beginners. Private Sub Form_Load() MsgBox "Hello, World!" End Sub

IT Learning Centre 46 Programming: Concepts for new programmers PG002

7.17. Ruby In the mid-nineties, Yukihiro Matsumoto wanted a language “more powerful than Perl, more object-oriented than Python”. Ruby grew in popularity in Japan for four years before gradually being taken up by English language developers. Overall, Ruby is closer to Perl than Python, though it shares Python’s “fun to program” ethos. “why's (poignant) Guide to Ruby” on the web is a stunning handbook for the language. puts 'Hello World!'

7.18. R Currently the world’s most popular “dedicated” programming language, R first appeared in 1993, the brainchild of Ross Ihaka and Robert Gentleman, but now maintained by the R Development Core Team. It is based on the S statistical programming language developed at Bell Labs in the mid-seventies and drives the leading specialist tool for statistics and data mining and its formidable graphical output capabilities including mathematical symbols. print("Hello World!", quote=FALSE)

7.19. Wolfram Wolfram, available in various forms since the eighties, is the dedicated programming language for Mathematica, a popular symbolic mathematical computation program. The Wolfram language is included with the , the Intel Edison module for wearables and the video game engine.

7.20. Haskell Literally designed by a committee, Haskell is modelled on an earlier, commercial program called Miranda where the whole program was based on equations grouped into functions - there are no statements. Functions called the same way always produce the same result and don’t interfere with each other (no “side effects”), so can be called in any order. Used to write Facebook’s anti-spam technology, Haskell is more readily associated with wide usage in academia. The leading implementation is the Glasgow Haskell Compiler, noted for its strength with concurrency and parallelism. $ vim helloworld.hs

main = putStrLn "Hello, World!"

47 IT Learning Centre PG002 Programming: Concepts for new programmers

8 Glossary Argument: A value that is passed to a function and which can then be used as input to the functions algorithm, or used to modify the function’s behaviour. Array: A data structure that collects together variables with the same type and name and arranges them (in human terms) in a multi-dimensional grid where each variable is accessed by index numbers. Assignment: The operation of placing a value into a variable. Most languages represent this by an = symbol, where what is on the right-hand side of the equals is assigned to the variable named on the left-hand side. Bootstrapping: When a computer is switched on, a program that is built into the hardware is run that enables the computer to then run other, more sophisticated, programs stored on media such as CD-ROMs and hard drives. Bug: An error in a program that causes it to behave in a way that was not intended Chip: The colloquial term for the integrated electronics (usually in the form of a small, manufactured block, or ‘chip’ of silicon-based material) that forms the basis for a computer Code: The keywords, symbols, variables, constants arranged in the appropriate structures to form the program. Comments: Text included in a program that reminds the programmer how a particular section of the program code works. The computer ignores any comments in a program. Compiler: A program which converts the program code statements into a format suitable for the computer to implement. Constant: Data which is included in a program but which cannot be changed (accidentally or on purpose) during the program execution. Debugging: The activity of finding and removing ‘bugs’ (errors) in a program. Disk: A storage medium that holds programs and data. There are many different types of disk (hard disk, floppy disk, CD-ROM, etc) some of which can be written to once and then cannot be changed, others of which are rewritable. Encapsulation: The term used to describe how objects in computer programs hide their internal properties and behaviour so that they can only be accessed in ‘safe’ ways. Execution: A program that is being followed by a computer is referred to as being ‘executed’. Compiled programs that are ready to be used by a computer are often referred to as ‘executables’. Function: A named collection of program statements that can be called from somewhere else in the program. This allows frequently used blocks of code to be written and tested once, and then used many times within a program. Interpreter: Many computer languages are translated as a whole into a form ready for the computer hardware to use by a compiler (see above). Some languages translate the program line by line as it is required. This is called interpreting a program and is done by an interpreter. Keyword: A word that is reserved for use by a particular computer language and which cannot then be used in any other way by a programmer (as a variable name for instance).

IT Learning Centre 48 Programming: Concepts for new programmers PG002

Library: A collection of prewritten programs that can be incorporated into a new program so save time writing and testing code that has been used before. Machine code: The format of a program that can be used directly by the computer processor. Memory: That part of the computer where data and programs are stored. See RAM and ROM. Object: In object-oriented languages (such as C++) an object is a self-contained block of code that models the behaviour and properties of a component of the solution to a problem. Object-oriented: A design method that models the real world problem area as closely as it can in terms of objects and their interactions with each other. Some languages such as C++ are particularly suited to using this type of design as a basis for the program code. Parameter: See Argument. Pre-test loop: A program structure which enables a group of statements to be repeated in a controlled way. The number of repetitions is controlled by a test condition. In a pre-test loop, the test is carried out at the start of the structure. This means that the code will never be executed if the condition is false initially. Program: The collection of program statements that a computer follows to carry out one or more tasks. Programming: The activity of designing, writing, testing, delivering and maintaining computer programs. Post-test loop: A program structure which enables a group of statements to be repeated in a controlled way. The number of repetitions is controlled by a test condition. In a post-test loop, the test is carried out at the end of the loop structure. This means that the code will always be executed at least once. Pseudocode: An informal English-like computer language that can be used to describe the activities and behaviour of a program during its initial development stages. Pseudocode is often included as comments in the final program to make it clearer how the program works. RAM: Random Access Memory. A storage area for programs and data that can be readily accessed and contents modified as needed. ROM: Read Only Memory. A storage area for programs and data that can only be accessed for reading and cannot be changed during the normal operation of the computer. The computer’s bootstrap program (see above) is stored in ROM. Selection: A program structure where one of several different sections of program code can be selected to be executed based on a predefined condition. Repetition: A program structure where a collection of statements are repeatedly executed until a predefined condition is met. Running: Colloquially, a program that is being executed is said to be ‘running’. Run-time: The period during which a program is being executed (see running above). Typically used in the phrase ‘a run-time error’, an error that occurred while the program was running. Sequence: A program structure where statements in the program code are carried out one after the other. This is the normal operation of a program when not influenced by a repetition or selection structure.

49 IT Learning Centre PG002 Programming: Concepts for new programmers

Statement: A set of related keywords and symbols typically written on a single line. Syntax: The rules of a computer language which govern which keywords and symbols can be used in what context. Variable: A named area of memory (usually RAM) of a size which can hold a particular type of data. The data held in that memory location can be referenced by simply using the variable name without needing to know the computer’s internal memory structure.

IT Learning Centre 50 Programming Today’s arrangements An introduction to the Concepts

Dave Baker Your teacher is [email protected] Your demonstrators are

We finish at

You should have Class notes

Copies of slides

IT Learning Programme

Your safety is important Your comfort is important

Where is the fire exit? The toilets are along the corridor outside the Beware of hazards: lecture rooms Tripping over bags and coats The rest area is where you registered; Please report any equipment faults to us it has vending machines and a water cooler Let us know if you have any other concerns The seats at the computers are adjustable You can adjust the monitors for height, tilt and brightness

This session assumes you know nothing about programming

the concepts of But by the end, we will have covered … programming What a programme is What a computer language is How we get computers to do what we want part 0 What we mean by data How programs reflect the real world introduction Or … Keywords, instructions and algorithms Sequence, selection and iteration Data, variables and constants Functions, objects and methods

1 There is no programming in this session We will not touch a keyboard

It is important that you focus on the ideas the concepts of not on the technicalities programming

The exercises are meant to be fun! part 1

what is a program? Discussion is an important part of the class

What is a program?

Is it … A list of instructions that can be understood and followed resulting in a predictable activity

exercise 1

Where do we find programs? Where do programs come from?

Most programs are written by people… …with the help of a program

ROM Processor Memory RAM ?

openclipart.org | paweo111 | public domain openclipart.org | dStulle | public domain

2 So, what is so difficult about programming?

People are illogical

and ambiguous

exercises 2, 3 Natural language is ambiguous

The word SET has 119 uses (dictionary.com)

There are four common types of error A syntax error breaks the rules of the we might introduce into a program language

Syntax In English, you should not say Run-time “The play what I wrote” Logic Semantic Debug Write In a computer language, you cannot say “The play what I wrote”

Test

A run-time error occurs when a A logic error occurs when the program program tries to do the impossible follows the wrong instructions

When a program is being followed Computers do not understand programs it is said to be Computers blindly follow instructions executing If you instruct a computer to do the wrong or running thing, it will do the wrong thing

A typical run-time error: To be frank about it: Trying to read data from a location without first checking All computer errors are human errors! that the location exists

3 A semantic error is a Writing (and debugging) is only a part misunderstanding on our part! of the software development process

What is the answer to: 3 + 4 * 5 Is it You were here 3 + 4 * 5 = 7 * 5 = 35 Or is it 3 + 4 * 5 = 3 + 20 = 23 The computer will always give the same correct answer

And there are many different software development processes

Questions so far?

© DSDM Consortium

What is a computer language?

the concepts of … the collection of words and symbols, and programming combinations of those words and symbols that can be used to describe a process that a part 10 computer should carry out

what is a computer language?

4 There are thousands of different Keywords and symbols are the core of a programming languages programming language

keyword symbols

double miles = kilometres * 0.621;

variables constant

www.digibarn.com/collections/posters/tongues/

An algorithm is a sequence of steps to Do androids dream of electric sheep? solve a particular problem Philip K Dick

For example: Prompt the program user for a temperature in Fahrenheit Check that the supplied information is a valid number Convert the temperature to Celsius Display the answer to the program user More typically: Subtract 32 and divide by 1.8 Or in a real language: sheep++; double temperatureC = (temperatureF – 32) / 1.8; sheep++; sheep++;

Image © Microsoft

Nobody thinks in a programming language Pseudocode should be readable and we use pseudocode instead understandable

You can define your own pseudocode language An example converting Fahrenheit to Celsius as long as it is Easy to read get a number from the program user Easy to understand check it is a number and more than or equal to -459.67 if it is not numeric or is less than -459.67 Unambiguous display a message to the user about the problem And the resulting pseudocode else Describes the what and not the how subtract 32 Avoids the use of specific programming language syntax divide by 1.8 display the answer on the screen

5 But there are many ways of expressing the same program

Another example converting Fahrenheit to Celsius

get TemperatureF if TemperatureF not numeric or TemperatureF less than -459.67 error message else TemperatureC becomes (TemperatureF – 32) / 1.8 exercises 4, 5 output TemperatureC

Programs have structure and there are three main types:

the concepts of Sequence Selection Repetition programming

part 11

controlling how a program behaves

Sequence is the normal operation of a Selection allows different paths to be program followed through the program

door is open? This statement Yes No followed by this statement switch on red light switch on green light followed by this statement sound warning buzzer

followed by this statement

6 Selection in pseudocode usually You can nest selections inside other involves if … then … else … selections

if the door is open then if between midnight and noon switch on the red light say ‘Good morning’ sound the warning buzzer else else if before 6pm switch on the green light say ‘Good afternoon’ end if else say ‘Good evening end if end if

You can nest selections as deeply Repetition comes in three forms as you want

if status is fulltime then if fulltime then pre-determined conditional holidays = 25 holidays = 25 commission = 0 else commission = 0 pre-test post-test if status is part-time then else if part-time then holidays = 13 holidays = 13 commission = 0 commission = 0 else if status is contractor then else if contractor then holidays = 0 holidays = 0 ? commission = 10% commission = 10% else else if consultant then if status = consultant then holidays = 0 holidays = 0 commission = 20% commission = 20% n else else holidays = 0 holidays = 0 commission = 0 ? end if commission = 0 end if end if end if end if

There are variations of Pre-test loops may never be pre-determined repetition carried out

for 3 times loop while bucket is not full sound buzzer add beaker of water end for n = 3 end loop for i = 1 to n sound buzzer next i So … we never add a beaker of water loop for each employee if the bucket is full increase salary by 5% end loop

7 Post-test loops are Make sure you choose the correct repeat always carried out at least once structure

loop loop add a beaker of water step forward end loop when bucket is full end loop when at edge of cliff !

So … loop while not at edge of cliff we always add at least one beaker of water step forward end loop

the concepts of programming

part 100

data exercise 6

A program generally has three stages Data that can change is represented by variables oxford42 299 792 458 Input A variable is a named area of memory Data is received/gathered Input speed that can be written by the program and read many times

Variables need Processing Processing to be large Algorithms act on the data life enough to accept the data Output cityName Good names are The results of the processing Output essential are made available Memory

8 Data that is fixed is represented Operators act on variables and constants by constants oxford42 299 792 458 A constant is a named = assignment area of memory that can be SPEED Before After written once and + addition read many times population 0 - subtraction urbanPopulation 1000 Constants need * multiplication LIFE to be large ruralPopulation 2000 enough to / division accept the data CITY_NAME Good NAMES are population = urbanPopulation + ruralPopulation essential Memory

In a program, data is assigned to a Good names and constants make variable programs more readable

TemperatureF = value from user Where are the variables, assignments, and if TemperatureF not numeric or TemperatureF < -459.67 operators here? Error message else TemperatureC = (TemperatureF – 32) / 1.8 TemperatureF = value from user output TemperatureC if TemperatureF not numeric or end if TemperatureF < -459.67 ABSOLUTE_ZERO = -459.67 TemperatureF = value from user Error message if TemperatureF not numeric or else TemperatureF < ABSOLUTE_ZERO TemperatureC = (TemperatureF – 32) / 1.8 Which is easier Error message else output TemperatureC to understand? end if TemperatureC = (TemperatureF – 32) / 1.8 output TemperatureC end if

Variables and constants handle many different types of data

Numerical Text Logical Objects whole characters yes – no video small words on – off music big notes true – false decimal documents small big currency exercise 7 dates

9 Data structures allow us to An array is a collection of variables with collect together related information the same name but different index 71519 There are many data structures available in programming languages One of the most useful is the array For example (0)temperature(1) (2) Instead of we can use temperature0 temperature(0) temperature1 temperature(1) temperature(0) = 7 temperature2 temperature(2) …… temperature(1) = 15 temperaturen temperature(n) temperature(2) = 19 why? Memory

Arrays are natural companions to Arrays can have more than one loop structures dimension 133742 rainfall(0,0) = 3 n = 120 rainfall(0,1) = 7 rainfall(0,2) = 4 rainfall(1,0) = 1 rainfall(1,1) = 2 7 15 19 for n from 0 to 2 (0,0) (0,1) (0,2) rainfall rainfall(1,2) = 3 Display temperature(n) (1,0) (1,1) (1,2) end for for column from 0 to 2 for row from 0 to 1 display cell contents 7 15 19 end for end for Memory Gives what?

Lists are simple to implement and easy to use

0 3 6

1 4 7 exercise 8

2 5 8

10 ‘Real world’ programs are as complicated as the real world

the concepts of Programs typically have many, many, MANY, programming statements Someone has to write all the statements! part 101 The statements must be easy to follow The program must be easy to maintain the ‘shape’ of programs

In the beginning, programs were Monolithic programs probably have monolithic (and some still are) repeated code

Start

using sequence But, hey! selection Isn’t that what repetition copy and paste is for? as appropriate

End

Functions are named blocks of code that Functions can be even more useful when simplify and help maintain large programs we make use of arguments

Program

Function

11 Functions help us to make our programs modular

exercise 9

Taking modularisation one step further gives us object-oriented programs

Questions?

www.youtube.com/watch?v=SS-9y0H3Si8

The best way to learning a programming language is to program!

the concepts of How do you choose a language to learn? programming Are there learning resources available? What is used on existing projects? part 110 Which language(s) are popular? Are the language skills in demand? Is there a mentor available? what next? How much does it cost Real money Time

12 The ITLP offers a number of programming For a gentle overview of programming language courses concepts, get to know Alice

C++ Java JavaScript Matlab Perl PHP Python See the course notes R for more details www.alice.org

Or you could try Scratch

Questions?

scratch.mit.edu

This presentation is made available under a Creative Commons Attribution-NonCommercial- ShareAlike CC BY-NC-SA licence by Dave Baker who asserts his right to be identified as the call exit() author. Note that some images used in the presentation are copyright of their owners and may be subject to different copyright conditions. Where possible this has been noted in the text. If an error in attribution/copyright has been made, please contact the author who will be pleased to make the necessary corrections.

13 [email protected]

14