Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

4 coding from algorithms

9,501 views

Published on

Published in: Technology
  • Be the first to comment

4 coding from algorithms

  1. 1. 4 Coding from algorithms Most good programmers do programming, not because they expect to get paid or get adulation by the public, but because it is fun to program. Linus Torvalds, developer of Linux Overview In the last unit we saw that an algorithm is a series of steps used to carry out a process or to solve a problem. In this we will go one step further and look at converting algorithms into programs so that the computer can complete tasks for us. To do this we will look at:  what a computer program is  the basic constructs needed to make a program  the role of sequence  using variables to store values  selection and nested selection  definite and indefinite iteration  subroutines  monopolies in the IT world. Programming languages A computer program is a series of instructions the computer follows to complete a task. The following program is written in C: int main() { printf("Hello world!n"); } This is the typical first program and simply outputs the words Hello world! on screen. As you can see there is more detail and punctuation in a computer program than in pseudocode. The reason for this is that the computer is an inanimate device and so instructions must be carefully constructed and precise enough to get it to do exactly what is required. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  2. 2. Coding from algorithms 95 Fundamentally the computer operates in a complex machine code of bits (0s and 1s) and bytes. Originally computers were programmed in what are now known as low level languages such as assembler. These languages produced machine code instructions that are difficult for ordinary people to work with. Nowadays programming is made easier through the use of high level languages. 1010 1100 1001 0010 ADDCC %r1,-4,%r1 count := 0; 0101 1100 0101 1111 MOV AL, 61h if total > 25 then 0010 1001 0110 1100 JMPL %r15+4,%r0 count := count + 1; machine code assembler high level language In IPT we are particularly interested in programming using third generation high level languages (3GL) such as C++, Delphi or Java. These languages are a way of instructing the computer in a consistent, English-like way that simplifies the task of writing software. Once you learn to program in a 3GL you will be able to give the computer instructions on what it is to do. These instructions will then be read by the computer and converted into machine code to direct the processor. There are two approaches to how a computer reads a program – compiling and interpreting. A compiled program is where the programmer’s instructions, the source code, as a whole are converted directly into machine code, the object code. This is done first. Only when ready is the object code then executed (run). As the source code is being compiled, the compiler (itself a program) will make changes to what was originally written, and many of the processes will be optimised to improve the speed of operation and data handling. The resulting compiled program will be smaller, faster, and more efficient. Unfortunately it is very difficult to un-optimise this compiled code to return to the original program; a little like unscrambling an egg. If the programmer wishes to make alterations these cannot be made to the compiled code, and so a copy of the original source code must be kept. When adjustments are made to the program the changed source code must then be re-compiled to be ready to run again. Examples of compiled programs include Delphi Pascal, C, C++ and Visual Basic. An interpreted program on the other hand is only changed into machine code as the program is running, usually one step at a time. Since the program is only interpreted line by line, on the fly, there is no optimisation. The object code is not as efficient as it could be. The advantage with interpreted languages is that any changes that have to be made in the program can be done without recompiling. This means there is a rapid turnaround time during development, and interpreted programs are more flexible and portable. (A portable language is one that can easily run on a range of computers.) Examples of interpreted programs include Java, Logo, Prolog, and the scripting languages such as PHP or JavaScript. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  3. 3. Leading Technology 96 Activity 4.1 – Talking my language 1. a What is a computer program? b Give examples of as many 3GLs as you can. 2. a Explain the difference between an high level and a low level programming language. b Which of these two forms produces source code, and which machine code? c What are the advantages and what are the disadvantages to programming in an assembler language? 3. a Find out what sort of language HTML and XML are. b Why are these not considered to be 3GLs? 4. a What does a compiler do? b What are the advantages of using a compiler? c How is an interpreted language different to a compiled language? d What are the advantages of using an interpreted language? Programming constructs If we hope to write computer programs the first thing to look at is how a program is put together. Many of the fundamental concepts on program design came from a Dutch railway engineer and programmer named Edsger Djikstra. He was the first to prove mathematically the following crucial theorem which is the basis of all third generation languages (3GL): Any problem that is solvable by a computer can be written using a combination of sequence, selection and iteration. Of these:  sequence – means step after step  selection – means being able to choose between alternative steps  iteration – means repeating some steps over. Djikstra liked to illustrate his ideas using trains as an analogy. It may help to think of programs this way with the steps of a program being the stations. A passenger in a train travels along a line visiting stations in sequence one after another. They go to one station, then the next, stopping at each in turn. For example on the London underground (at right and over page) trains will visit Queensway, then Lancaster Gate, then Marble Arch, Bond Street, and so on. A train cannot be at two stations at the same time, and it must leave one station before going to the next. In the same way a 3GL computer program can run only one instruction at a time; when this is finished it moves onto the next instruction in the sequence. Edsger Djikstra © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  4. 4. Coding from algorithms 97 At some points a passenger can change from one line to another. On the underground map these are indicated by circles, such as at Green Park or Oxford Circus. At these points the passenger can stay on the line they are on, or choose (select) to move to a different line, and thus visit a different set of stations. A section of the London Underground map. In a 3GL the program can also branch, or offer a selection of two or more alternative sets of instructions to carry out. Finally the underground has loops in it that allow passengers to go round and round repeatedly visiting the same stations over again as long as they wish. A 3GL can also iterate, or repeat the same instructions over and over until told to jump out of the loop. To repeat Djikstra’s theorem, any computer solvable problem can be written using sequence, selection and iteration. This means that if you know how to do just these three things in a computer language, you can write any program. In this unit we will investigate sequence, selection and iteration in algorithms and see how to link these into computer programs. More pseudocode As seen in the last unit, pseudocode is a simplified means of representing the steps in a computer program. Pseudocode is independent of any single computer language but, if designed correctly, can be used to help prepare code for most 3GLs. In the sections that follow we will see pseudocode used to represent sequence by placing each new instruction on a separate line, to represent selection using if and case statements, and iteration using while and repeat loops. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  5. 5. Leading Technology 98 While there is no set standard for pseudocode, it should be consistent, simple and clear. The basic commands in pseudocode are for input, output and assignment:  input – use the word get followed by the variable to store the input value in e.g. get value so that the user knows what to do, it is a good idea as part of the HCI to precede the input line with a prompt e.g. prompt for value  output – use the word write or print followed by the words or values to be displayed; write is used for screen output, print for output to printer e.g. write value or print "The value is ", value values to be output must be separated with commas; any output text is to be enclosed in quotes; (output text is called a literal because it is presented exactly as it is)  assignment – use an equals sign = with a variable on the left and the calculation to its right e.g. value = value + 1 the result of the calculation is stored in the variable on the left. In pseudocode, and in most computer programs, the normal rules of Maths apply, with calculations in brackets evaluated first, then powers, multiplication, or division, and finally addition or subtraction. Note also that * is used for multiply. This is normal computer usage. In turn we use / to indicate division. (Why do you think these are necessary? Can you find on the keyboard?) A complete listing of the pseudocode used in this text is found in Appendix 3, along with a link to a program that can execute pseudocode. Sequence In sequence means steps are performed one after another, in a set order, and that no two steps happen at the same time. Using pseudocode we indicate the sequence by writing each new step on a separate line. If we wished to get the computer to calculate someone’s age we might use the following pseudocode that demonstrates sequence. prompt for currentYear get currentYear prompt for yearBorn get yearBorn age = currentYear – yearBorn write "Your current age is ", age, " years old" The algorithm starts by asking the user what is the current year. The value the user enters is stored in the variable currentYear. The user is then prompted for their year of birth which is stored in yearBorn. The fifth line assigns the result of the calculation in age, while the last line outputs the result. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  6. 6. Coding from algorithms 99 When this pseudocode is converted into a computer language and run, each step must be completed before the next commences. The order is important. If the last three lines were out of order an error would occur (why?) and the algorithm would not work. In addition to pseudocode we can represent sequence graphically. Pseudocode Flowchart prompt for currentYear get currentYear prompt for yearBorn get yearBorn age = currentYear - yearBorn write age Nassi–Shneiderman Diagram Structured Design Chart Three graphical representations of the age pseudocode input currentYear input yearBorn output age age = currentYear - yearBorn Input currentYear Input yearBorn age = currentYear – yearBorn Output age Calculate age Input data Calculate Output result Get currentYear Get yearBorn age = currentYear - yearBorn Output age © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  7. 7. Leading Technology 100 Various 3GL implementations of the age pseudocode C++ #include <iostream> using namespace std; int main () { int yearBorn; int currentYear; int age; cout << "What is the current year? "; cin >> currentYear; cout << "What is your year of birth? "; cin >> yearBorn; age = currentYear - yearBorn; cout << "You are currently " << age << " years old!" << endl; } Java import java.io.BufferedReader; import java.io.InputStreamReader; public class age { public static void main(String[] args) { BufferedReader br; int currentYear = 0; int yearBorn = 0; System.out.print("What is the current year? "); try { br = new BufferedReader(new InputStreamReader(System.in)); currentYear = Integer.parseInt(br.readLine()); } catch(Exception e) { System.out.println("There was an error processing your input"); return; } System.out.print("What year were you born? "); try { br = new BufferedReader(new InputStreamReader(System.in)); yearBorn = Integer.parseInt(br.readLine()); } catch(Exception e) { System.out.println("There was an error processing your input"); return; } int age = currentYear - yearBorn; System.out.println("You are " + age + " years old!"); } } PHP <?php fwrite(STDOUT, "What is the current year? "); $currentYear = trim(fgets(STDIN)); fwrite(STDOUT, "What year were you born? "); $yearBorn = trim(fgets(STDIN)); $age = $currentYear - $yearBorn; print("You are $age years old!n"); ?> Delphi Pascal procedure TAreaForm.CalcButtonClick(Sender: TObject); var currentYear, yearBorn, age : real; begin currentYear:= StrToInt(InputBox(‘Get now’, ‘Enter the current year’, ‘ ‘)); yearBorn := StrToInt(InputBox(‘Get birth, ‘Enter the year of your birth’, ‘ ‘)); age := currentYear - yearBorn; CEdit.Text := ‘You are now aged ‘ + FloatToStr(age); end; Visual Basic Private Sub CalcButton_Click() Dim CurrentYear, YearBorn, Age As Single CurrentYear = Val(YearText.Text) YearBorn = Val(BirthText.Text) Age = CurrentYear - YearBorn AgeLabel.Caption = ‘You are now aged ‘ + Age End Sub © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  8. 8. Coding from algorithms 101 Activity 4.2 – One thing after another 1. What would be output by each of the following pseudocode examples?: a prompt for hoursWorked get hoursWorked prompt for payRate get hoursWorked pay = hoursWorked * payRate write "You will receive $", pay b prompt for time get time quarters = time * 4 cost = quarters * 15 + 35 write "The cost of service is $", cost c prompt for first get first prompt for second get second prompt for third get third total = first + second + third average = total / 3 write "The average of the numbers is ", average 2. Prepare pseudocode for an algorithm that will get the user to enter the price of an item for sale. The program will then calculate the GST for the item, and output the selling price of the item that includes the GST. 3. If a matchbox contains 45 matches write the pseudocode for an algorithm to calculate how many matches there will be in the number of matchboxes the user enters. For example: if the user enters 10 matchboxes, the value 450 matches will be output. 4. Australia now uses the metric system. In the past length was measured in feet and inches. An inch is about 2.54 cm, and there are 12 inches in one foot. Prepare the pseudocode for an algorithm to get the user to enter feet, then inches. This must then be converted to inches only. For example: if the user enters 2 feet 5 inches this will be converted to 2 x 12 + 5 = 29 inches. These inches must then be converted to centimetres (e.g. 29 x 2.54 = 73.66). Finally output the result. Your algorithm must work with any values the user enters. 5. The calculation to convert degrees Fahrenheit to degrees Celsius is to subtract 32, multiply this answer by 5, then divide that answer by 9. For example 85o F is 29.4o C. (85 – 32 = 53; 53 x 5 = 265; 265 ÷ 9 = 29.4) Prepare the pseudocode for an algorithm to convert degrees Fahrenheit to Celsius. 6. Convert the pseudocode for the above three questions into a 3GL of your choice. The user enters 5 for the hours and 25.50 for the rate The user enters 3 hours for time. The user enters the values 15, 6 and 13 © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  9. 9. Leading Technology 102 Using variables The above activities demonstrate not only the first programming construct of sequence, but also the use of variables. While we are not too concerned with the detail of variables in pseudocode, other than that they are a named way to store a value, when converting pseudocode to a programming language we have to be more aware of what is involved in using them. Types of variable The main characteristic of a variable used in a 3GL is that it can be one of several different types. To illustrate this we will use the following pseudocode: prompt for name get name prompt for age get age time = age * 1144.5 write name, " you have watched about ", time, " hours of TV in your life." This algorithm determines the amount of TV watched based on the statistic that Australians watch on average 1144.5 hours of TV a year. For example if the user enters Mary for name and 16 for age the algorithm will produce: Mary you have watched 17167.5 hours of TV in your life. The algorithm uses three different variables, name, age, and time. Each of these holds different sorts of values. Name holds text, age holds whole numbers, while time can hold decimal values. Depending on the programming language chosen there are a wide variety of different forms of variable that can be used. For now we will look at only these three basic types. Int or Integer Variables of this type are like age above and will hold whole number values, e.g. 34, -56, 26 614. We can add (+), subtract (-) and multiply (*) integers, but the normal operation of division (/) will result in an error (why?). Functions such as div and mod are usually used for integer division; the result is a whole number (e.g. 17 div 5 is 3; 17 mod 5 is 2). Real or Float or Single This form of variable, like time above, holds decimal values, e.g. 23.4, -1456.678, 28.0. These are stored in memory as floating point numbers which are a binary form of exponential or scientific notation (i.e. similar to 2.14 x 1023 , but using 0s and 1s). String or Char This type is like name above and will hold text, e.g. Brisbane, Alice, 39 Devon St. There are operations and functions we can use on strings such as joining two strings (called concatenation), or finding out how long a string is. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  10. 10. Coding from algorithms 103 In storing a value in a string variable it is usual to use either single or double quotes (depending on language). These show the start and end of the text, and clearly indicate any spaces in the string, e.g. address = "39 Devon St" In addition to the above there are many other variable types available depending on the programming language used. They include shortint, double, byte, Boolean, currency, shortstring, word and many more. Some languages also have the option of creating your own types of variables. Variable declaration In most programming languages it is necessary to tell the program what sort of values it will come across before it uses them. We do this in the variable declaration. The declaration tells the compiler or interpreter the name of a variable and the type of value it will hold. A variable declaration can only be made in certain specified places, usually near the beginning of a program or procedure. (See the examples on page 100.) When preparing a variable declaration it is important to ensure the setting out and punctuation is exact. You will be making many of them, and missing a comma or misspelling a type will cause an error in the program. This may seem to be overly exact, but this is the way it must be if the compiler or interpreter is to accept it. Computer languages demand the discipline of being precise and accurate. Once you have declared a variable you should not then deviate from its type. You cannot for example declare a variable as a string and then try to divide into it. If you declare one as an integer, you may cause an error if you try to store a decimal value in it as a result of a calculation. In making a formal declaration we are indicating exactly what sort of values we are dealing with and what operations can be performed on variables. Not only do we reduce potential errors, we ensure we develop clear effective code, adding to the internal documentation of our program. Despite this some programming languages do not require a variable declaration. The program determines the type a variable is, from the values it is called upon to store. This is known as an implicit declaration or sometimes as a dynamic declaration. If for example the first time a program comes across a variable it is called upon to store text, then that variable is treated as a string or char variable. The same applies for integer, floating point or other types of variable. While an implicit declaration saves the time it would have taken to make a normal variable declaration, it is generally seen as poor programming practice. Not making an explicit declaration can lead to errors. One common mistake with an implicit declaration is that, when using a variable again later in the program, it is misspelled. The compiler will treat the misspelling as a new variable, and the calculation or assignment will not do what was intended. Another possible error is a type mismatch, where the program treats a variable as one type when the programmer intended something else. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  11. 11. Leading Technology 104 Constants In addition to variables it is sometimes useful to use constants. If we know a value will always be the same and will not change as the program is running we can give it a name and declare it as a constant. It might seem strange to do this when we could just use the value itself, but the use of constants has several advantages. One benefit is that if a key value a program is based is changed then, by simply altering one value in one place, every use of the value in the rest of the program does not have to be altered. For example a program may be many thousands of lines long with frequent references to the company tax rate. If the government then changes the tax rate from, say, 29% to 28%, the program would have to be searched through for every reference to 29%. If the tax rate is set as a constant at the beginning, then only the one value in the constant declaration needs be changed. Another advantage of using constants is that referring to a named value is easier to understand than just using the value itself. For example: payment := income * taxRate; makes it easier to understand what is going on in a program than say: payment := income * 0.29; Constants can be declared at the same time as variables. In larger programs that contain many sub-programs the constant declaration for all parts of the program is usually done in the one place. (See the section on scope later.) Comments A comment is a note or a reminder added to a program to make it more understandable to anyone reading the code. Comments usually begin with a special marker or are included in between markers. C, C++, Java, PHP, etc. Perl, Ruby, etc. /* * The following section of program * determines the total amount owing */ =begin The following section of program determines the total amount owing =cut Pascal Basic, Visual Basic { The following section of program determines the total amount owing } REM The following section of program REM determines the total amount owing Examples of comments in various 3GLs You can also add a comment to an existing line of code. e.g. Pascal: value =: amount /100; // convert to percentage VB: value = amount /100 ' convert to percentage This is known as an inline comment. Inline comments usually explain just what is happening in that one line of code. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  12. 12. Coding from algorithms 105 Comments are ignored by the computer. Their main purpose is to make the program easier to understand. In addition to giving information about what is going on in a program comments can be used when trying to trap or localise errors in an existing program. If you suspect a part of a program is at fault, you can turn that part into a comment by adding the comment identifiers. If, when the program is run with this section commented out, and the error does not occur, you can pinpoint where the error is. e.g. if (milesTravelled <= 100) { priceLessThan100 = milesTravelled * lessThan100; priceMoreThan100 = 0; // } else { // priceLessThan100 = 100 * pessThan100; // priceMoreThan100 = (milesTravelled + 100) * moreThan100; } Commenting out is a very useful debugging technique. In pseudocode a comment is indicated with a # symbol, e.g. # this is a comment . Naming variables Comments are part of the internal documentation of a program. As mentioned in the previous unit, internal documentation is anything within the code itself. Another form of internal documentation is to use meaningful identifiers for variable names. Look at the following two ways of writing a line of a program, here in Visual Basic: w = h * p WeeklyPay = HoursWorked * PayRate They both do exactly the same calculation, but in which of the two is it easier to understand what is going on? Of the two the second has the advantage of indicating not only what sort of values are being used, but what the calculation achieves. This can make a program more understandable to someone reading the code, especially since programs can consist of hundreds of lines and dozens of variables. It is important that when you create variables you chose the names carefully. Variable names should reflect the type of information they will hold. Total has much more meaning than T, averageAge has more meaning than A. Meaningful variables names make a program easier to understand and should be part of the internal documentation of any program you write. Depending on the language you use there are also some restrictions on variable names and some conventions on how they should be used. The restrictions may include limitations on start character, or on the use of punctuation marks or special characters. Almost all languages for example will not allow variable names to start with a number, while many languages will not permit the use of characters such as # or @. Some languages have reserved words, i.e. words such as begin or endif that can only be used in certain ways and not used as variable names. else section commented out © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  13. 13. Leading Technology 106 Since meaningful identifiers for variables can be several words long, and since most languages do not permit blanks in variable names, programmers have adopted different ways, or conventions, of how to display these. The two most common are:  camel case – the words are capitalised like the humps of a camel, e.g. annualTaxRate  underscore – words are separated by the _ character, e.g. annual_tax_rate In addition some programmers use the convention of identifying the type of variable in the variable name, e.g. strUserName (string), intTotal_Count (integer). This is less common nowadays. In each of these examples the method used is only a convention, an accepted style, and is not a requirement of the language. This means you can adopt the style that suits you and helps you communicate what you are doing to anyone who will read your code. Activity 4.3 – Variables For this activity use a 3GL of your own choice. 1. What type should you declare each of the following variables – integer, real/float, or string/char? Examples of typical values each will hold are given in the brackets. a average_age (3.4, 12.75) b totalScore (-16, 345) c name (Fred, Ann) d answer (-36.5432) e bird_type (swallow, hawk) f phoneNumber ( (07) 4261 3491 ) g last (879, -1234) h result (56.98, 123) i colour (purple, green) j amountOwing ($345.45) 2. For the samples below the variables result, number, and answer are declared are integers. If result holds 23 and number holds 6 what would answer hold after each of the following?: a answer = result div number b answer = result mod number c answer = number mod result d answer = number div result 3. Write a separate declaration for each of the following: a first and second are integers and third is a decimal number. b position will hold the title of a person in the organisation. c amount, bonus, count and due are all variables that will hold decimal numbers. d age is an integer, hold and last are text, maxValue, total and average are decimals. 4. Prepare declarations that will do the following: a Record the name, age in years, height (e.g. 1.54m), and address of people in your class. b Record a soccer team’s name, score in last game, total goals for season, and average score. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  14. 14. Coding from algorithms 107 c A menu for a game that will ask for a player’s name, what skill level she wants to play at (1, 2, 3, etc.), and if they wish to have another go at the game (true/false). 5. Denise’s Discount Dress Shop has a policy of discounting all items sold. Some dresses are discounted by 10%, some by 15% etc. Denise would like a program where she and her assistants can enter the price of the dress and the rate of discount to find out the selling price. To solve this problem there are two steps that have to be carried out, the calculation of the amount of discount and then the actual selling price. In pseudocode the algorithm is: prompt for cost get cost prompt for rate get rate discount = rate * cost sell_price = cost - discount write "The selling price is $", sell_price Prepare an application for Denise whereby she can enter the cost and the discount rate to have the selling price displayed. (Hint: be careful with rate; it will need to be entered as a decimal e.g. 0.1 for 10%, or if entered as a whole number then divided by 100.) Add suitable comments to this program to explain what is going on. 6. Mike’s Mini-Skips is a rubbish removal company. Mike charges $38 for the skip for the first day, plus $15 each extra day. He then charges 35c per kilometre to take the rubbish to the dump. Prepare the pseudocode and then write a program from this to calculate his charges. Use appropriate internal documentation. Hint: charge = 38 + ( 15 * days ) + ( km * 0.35 ) 7. Mary operates an import business. She always adds 25% onto the price of goods as her commission and to cover costs. Prepare the pseudocode and then write a program that allows Mary to enter the name of an imported item, its landed cost, the number of items, and then displays this information and outputs her total profit. 8. Cyril’s Cycles hires out push bikes at $18.60 per hour. Prepare the pseudocode and write a program with effective internal documentation that allows Cyril to enter the time-out and time-in of a bike, and calculates the cost of hire. To simplify this program you may use 24 hour time, e.g. 2 p.m. is 1400 hours. If you do, be careful: 0945 to 1415 is six and a half hours, not 1430 minus 0945! Selection There are times in the running of a program when we wish to make a choice between one of two or more possible steps to follow. The program will then select which path to follow. At the end of the branching the program will return to a single pathway. You may recall Djikstra’s © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  15. 15. Leading Technology 108 train coming to a junction. Depending on which branch is chosen, different stations will be visited. To decide between the paths, a question needs to be asked which can only be answered true or false. The question is known as a condition. As an example the following pseudocode decides if a student will pass or fail a test based on her test result: if result > 50 then write "Pass" else write "Fail" endif The condition if result > 50 asks the question Is the result more than 50? If yes, this is true, then the student passes; if no, it is false, then the student fails, and the algorithm outputs the result. To record selection pseudocode uses the keywords if, then, else and endif. The if is followed by the condition to be tested. If the condition is true the steps after the then are carried out. If the condition is false the steps after the else are run. The condition must be such that is can only be satisfied by true or false. In pseudocode the if statement is concluded by the endif keyword. The logic of the selection can been seen graphically below Pseudocode Flowchart prompt for result get result if result > 50 then write "Pass" else write "Fail" endif Nassi–Shneiderman Diagram (and Structure Design Charts) Graphical representations of selection if score > 50 input score write "Pass" write "Fail" Input score if score > 50 T F Output Output "Pass" "Fail" prompt for score T F © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  16. 16. Coding from algorithms 109 Note that it is usual to indent (move in) the steps that belong to the then or the else sections. This is not a necessity, but the indentation makes it easier to see the parts of the program that belong together, especially if there is more than one step in either the then or the else part. Indentation is also part of the internal documentation of a program and is an important part of communicating the program’s meaning to others. In pseudocode the conditions that are recognised in selection statements are: == is the same as < is less than < = is less than or equal to < > is not the same as > is greater than > = is greater than or equal to e.g. if age <= 18 then... i.e. if the value in age is less than or the same as 18 do the then part. The logical operators of and and or can also be used to combine conditions. e.g. if (age < 18) and (gender == "F") then or if (name == "Michael") or (name == "Mike") then The brackets make clear which conditions are to be combined. The else part of the if statement is optional. For example: Weather check look out of window if raining then get umbrella walk out through door In this algorithm the else is left off because, if it is not raining, you will not need an umbrella and so nothing is done. An if statement with no else part is called a skip, i.e. do nothing. In pseudocode and most 3GLs the else is simply omitted: e.g. if count < 20 then total := total + 1; The following examples demonstrate the use of selection in a range of 3GLs: Pseudocode prompt for result get result if result > 50 then write "Pass" else write "Fail" endif Delphi Pascal result := StrToInt(ResultEdit.Text); if result > 50 then ResultLabel.Caption := ‘Pass’ else ResultLabel.Caption := ‘Fail’; Visual Basic Result = Val(ResultText.Text) If Result > 50 Then ResultLabel.Caption = "Pass" Else ResultLabel.Caption = "Fail" End If © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  17. 17. Leading Technology 110 PHP: <?php fwrite(STDOUT, "Enter your result: "); $result = trim(fgets(STDIN)); if ($result > 50) { echo "Passn"; } else { echo "Failn"; } ?> C++: cout >> "Enter your result: "; cin << result; if (result > 50) { cout << "Pass" << endl; } else { cout << "Fail" << endl; } Pseudocode if (attempts < 3) and (password == "Jumbo5") then write "Access permitted" else write "Access denied" endif JAVA if (attempts < 3 && password.equals("Jumbo5")) { System.out.println("Access permitted!"); } else { System.err.println("Access denied!"); } PHP if ($attempts < 3 && $password == "Jumbo5") { echo "Access permitted!n"; } else { echo "Access denied!n"; } Pseudocode if (age < 0) or (age > 120) then write "Invalid age entered" else months = age * 12 endif C++ if (age < 0 || age > 120) { cout << "Invalid age entered" << endl; } else { months = age * 12; cout << months << endl; } Pascal if (age < 0) or (age > 120) do writeln("Invalid age entered") else months := age * 12; © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  18. 18. Coding from algorithms 111 Activity 4.4 – Pseudocode selection 1. What would be output at the end of each of these situations: a score = 25 if score > 30 then write "Expert level" else write "Novice level" endif b answer = 15 newAnswer = answer * 3 / 2 if newAnswer == 22.5 then write "Correct" else write "Wrong" endif c name = "Fred" if name < > "Fred" then new_name = "Mick" else new_name = "Tom" endif write new_name 2. What would be output as a result of the following segment an algorithm? one = 10 two = 20 if not (one > 12) and (two == 20) then write "Okay" else write "No way" endif 3. Convert the following pseudocode to code in a 3GL. prompt for age get age prompt for hoursWorked get hoursWorked if age < 18 then category = "Junior" payRate = 8.50 else category = "Senior" payRate = 12.75 endif pay = hoursWorked * payRate write "You will work in a " , category, " capacity with $", pay, " pay" 4. Design the pseudocode to read any three input numbers and then display the largest of them. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  19. 19. Leading Technology 112 5. TopNotch travelling salesmen are paid a flat salary of $100 per week, plus $15 for every 100 widgets they sell. In addition they receive a bonus of $50 if they sell over 1000. The area supervisor for TopNotch needs a program so that she can enter the number of widgets a salesman has sold, and then find out how much to pay him. Design the solution to the above problem using pseudocode and then code this in a 3GL program with effective internal documentation. 6. We want to calculate an electricity bill based on the number of units of electricity used. Electricity is charged at different rates depending how much is used, the more used the cheaper it is. This can be seen on the following scale:  11.2c for the first 1000 units  9.7c for the next 500 units, and  6.8c for units in excess of 1501. For example if the household uses 1350 units of electricity it will cost: 1000 x 11.2c + 350 x 9.7c = $145.95 if they use 1875 units it will cost: 1000 x 11.2c + 500 x 9.7c + 375 x 6.8c = $186.00 If we make the assumption that a household uses at least 1 000 units then the pseudocode for the solution is: prompt for units get units cost = 1000 * 11.2 remainder = units - 1000 if remainder > 500 then cost = cost + (500 * 9.7) remainder = remainder - 500 else cost = cost + (remainder * 9.7) remainder = 0 endif if remainder > 0 then cost = cost + (remainder * 6.8) endif cost = cost / 100 #convert to $ write "The cost of electricity for ", units, " units is $", cost The second line works out the cost for the first 1 000 units. The next line finds out how many more than 1 000 units have been used and stores the result in the variable remainder. The first if statement then calculates the charge for the next 500 units (then) or part of 500 (else). If there are over 1 500 units the then section finds how many still have to be calculated (remainder). The second if calculates charges for usage over 1500 units, if any. There has to be a pseudocode endif for each if statement. The / 100 is used to convert the answer to dollars. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  20. 20. Coding from algorithms 113 a Create the program to go with this pseudocode. Enter values such as 1850 (the answer should be: $184.30); 2205 ($208.44) and 1100 ($121.70). b As the program stands if you enter values less than 1 000 it gives strange values. Why is this? Correct this error by the use of an if statement to handle values less than 1 000 units. More selection For more complicated decisions we can use a nested if selection, i.e. one selection is inside of another. Nesting selections is one way of including more complex pathways in a program. The following pseudocode shows an algorithm with nested selection: prompt for result get result if result < 50 then write "Fail" else if result > 80 then write "Credit" else write "Pass" endif endif As you can see the first else contains a selection of its own which will only be carried out if the result is not < 50. In this case (i.e. result > 50) the student will get a credit if she scores over 80, otherwise she will pass. Note how the indentation assists in showing which part of the code belongs to which then or else. Note also there is no need to specify that a pass grade is awarded for marks between 50 and 80. (Why not?) As you can imagine, as decisions get more complex if...then...else selections can get nested to three, four or more levels making the algorithm, or program built form it, very difficult to follow. If we wish to give students an A to E ranking then the final version of our test result algorithm might look like: prompt for result get result if result < 30 then write "E" else if (result > 30) and (result < 50) then write "D" else if (result > 50) and (result < 65) then write "C" © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  21. 21. Leading Technology 114 else if (result > 65) and (result < 80) then write "B" else write "A" endif endif endif endif When things get this complicated some 3GLs can use a case selection as is shown in this algorithm: prompt for result get result case of result 1 to 30 : write "E" 31 to 50 : write "D" 51 to 65 : write "C" 66 to 80 : write "B" 81 to 100 : write "A" endcase The case selection moves down the list of possible choices until it finds one that meets the condition. At first result is compared to numbers between 1 and 30, next to numbers between 31 and 50, and so on. When a match is found the associated step is carried out. Control then jumps to the end of the statement, ignoring the rest. We can even add a step to the case statement to cover the situation where there are no matches: : 81 to 100 : write "A" other: write "Invalid value entered" endcase This will cover the possibility of someone entering a number not between 1 and 100. This is part of what is known as user proofing a program. Case selection is very useful for choosing one of a series of possible pathways a program could follow. Things to note about using it:  not all 3GLs support a case statement  the variable in the condition usually must be an ordinal (counting) type such as an integer or a char  each possible choice is followed by a colon : and then what to do  depending on language used, for each choice we can test numbers, strings, variables, a range of values (as above), or a list of values separated by commas  as soon as any condition is met the rest are ignored; if there are no matches the other statement, if there is one, is carried out. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  22. 22. Coding from algorithms 115 Nassi-Shneiderman representation of a case selection Delphi Pascal case result of 1..30 : ResultLabel.Caption := ‘E’; 31..50 : ResultLabel.Caption := ‘D’; 51..65 : ResultLabel.Caption := ‘C’; 51..80 : ResultLabel.Caption := ‘B’; 81..100 : ResultLabel.Caption := ‘A’; else ResultLabel.Caption := ('Invalid value'); end; VB Select Case Result Case 1 to 30 OutputText.Caption = "E" Case 31 to 50 OutputText.Caption = "D" Case 51 to 65 OutputText.Caption = "C" Case 66 to 80 OutputText.Caption = "B" Case 81 to 100 OutputText.Caption = "A" Case Else OutputText.Caption = "Invalid value’ End Select The Case statement in two 3GLs Activity 4.5 – Very choice 1. a Convert the following pseudocode to a suitable 3GL: prompt for rating get rating prompt for age get age if (rating == "R") and (age < 18) then write "You are too young to see this movie" else if (rating == "M") and (age < 15) then write "You must be accompanied by a parent for this movie " else write "You can view this movie" endif endif b Extend the program to cover other movie classifications. Input score Case score 1-30 31-50 51-65 66-80 81-100 other Output Output Output Output Output Output E D C B A invalid © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  23. 23. Leading Technology 116 2. Plan and write a program using a case statement (or nested if statements) to get the user to enter any number between 1 and 10, and then convert it into Roman numerals, e.g. 7 is converted to VII. 3. Sales reps are often paid on an incentive scheme similar to the following:  if sales are under $5 500 they receive 3% commission  if between $5 510-$9 000 they receive 5% commission  if sales are over $9 001 they are paid 7% commission. e.g. for sales of $8 500 the sales rep would receive 3% commission for the first $5 500 and 5% for the remaining $3 000; i.e. 3% x $5 500 + 5% x $3 000 = $165 +$150 = $315. Prepare a program to read the sales made for a particular day, and then calculate and display the commission to be paid. Include effective internal documentation. Iteration By now you must be beginning to think computers are pretty useless objects. To get them to do even the simplest task requires thinking, planning, typing, correcting and so on, when you could have done the whole job yourself in a few seconds. The real power of the computer however is in its speed. The programs you have run so far have been executed by the computer in a few millionths of a second! What we need to do, to tap into this amazing speed is to give it more things to do. Now it is impractical to type out a program thousands of lines long, but what if we get the computer to do a set task, or group of tasks, until we tell it to stop. We can get it to repeat the same set of instructions over and over again, usually with a slight change each time. By getting it to loop back on itself, it can, if necessary, repeat the same few lines as many times as we like. Again recalling Djikstra’s train, this time the train would be switched onto a circular section of track and would run around the loop visiting the same stations again and again until the switch was set to return it to the main line. Looping back to repeat steps is called iteration or repetition. Iteration can occur a set number of times (definite iteration), or until a specified condition occurs (indefinite iteration). The While loop There are several ways of performing iteration in a 3GL. We will look at three, beginning with while. The following algorithm demonstrates a while loop to count from 1 to 500: number = 1 while number < 501 write number number = number + 1 endwhile © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  24. 24. Coding from algorithms 117 The while tells the computer to keep doing what follows until a certain condition is met, in this case while the variable number is less than 501. (Why is it necessary to set number equal to 1 before entering the loop?) The key pseudocode words for this type of iteration are while and do with a condition in between them. The conditions that are recognised are the same as for selection ( = , < > , < = , etc.). Indentation and endwhile show the steps to be repeated. Again this indentation is not necessary, but it shows the instructions that belong together and act as a group. In writing a while loop be careful that the loop will end. What is wrong with the following pseudocode to output odd numbers less than 20? number = 1 while number < >20 write number number = number + 2 endwhile The value in number will increase by 2 each time, but it will never equal 20 exactly. In this case the computer would keep on going forever! In a situation such as this we say the program is caught in an infinite loop. In each of these cases the first line (number = 1) assigns a value to a variable. This is necessary so that the condition can be tested. This assigning of a value before the loop is run is called initialising the variable, i.e. setting its initial or beginning value. (Note: in some 3GLs you can initialise variables as part of the declaration.) In computer code the while loop will look like: PHP $number = 1; while ($number < 501) { echo $number++; } C++ int number = 1; while (number < 501) { cout << number++ << endl; } Pascal number := 1; while number < 501 do begin writeln(number); number := number+1: end; The Repeat loop The while loop is an example of pre-tested iteration. This means the condition is tested before the loop runs. If the condition is false the steps in the while loop will not be carried out. The alternative to pre-tested iteration is post-tested, where the loop runs at least once before the condition is tested. The usual construct for post-tested iteration is repeat ...until. number = 1 repeat write number number = number + 1 until number = 501 © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  25. 25. Leading Technology 118 The repeat loop will produce the same output as the while loop, but in this form of loop the condition is not checked until after the steps to be repeated have been carried out at least once. Note there is no need for an endrepeat keyword in the pseudocode as the until shows where the loop will end. We can use either pre-tested or post-tested iteration depending on which is better to solve the problem we are working on at the time. The major difference between them is that in post- tested iteration the steps to be repeated are run at least once. With pre-tested they might not even run one time. (Why not?) In computer code post-tested iteration will look like: VB Number = 1 Do Out.Text = Number Number = Number + 1 Loop Until Number = 501 C++ int number = 1; do { cout << number << endl; number = number + 1; } while(number < 501); PHP <?php $number = 1; do { echo "$numbern"; $number = $number + 1; } while ($number < 501); ?> Graphical representations of pre- and post-tested iteration are shown on the next page. Activity 4.6 – Totalled 1. Prepare a program to total a series of input positive numbers. The user is to enter a negative number to finish and get the total. The pseudocode for the operation is: prompt for number get number total = 0 while number >= 0 total = total + number prompt for number get number endwhile write "The total is ", total 2. Prepare the pseudocode to input a set of test marks. The algorithm must report the average mark of the students and also the highest mark. Get the user to enter a negative number to finish the loop. Hint: if mark > max then max = mark Convert the pseudocode into a 3GL with appropriate internal documentation. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  26. 26. Coding from algorithms 119 Pre-tested iteration number = 1 while number < 501 write number number = number + 1 endwhile F T Post-tested iteration number = 1 repeat write number number = number + 1 until number = 501 T F Graphical representations of pre- and post-tested iteration if number < 501 write number number = 1 while number < 501 number = 1 write number if number < 501 write number number = 1 number = 1 while number < 501 write number © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  27. 27. Leading Technology 120 3. The following algorithm uses a while loop to control a guess the number game in which the user is given 10 guesses to pick a random number between 1 and 1000.. number = random (1000) correct = 0 count = 1 while (count < 11) and (correct == 0) prompt for guess get guess if guess == number then write "Correct – Well Done" correct = 1 else if guess < number then write "Too low" else write "Too high" endif endif count = count + 1 endwhile write "The number was ", number This algorithm uses two variables, correct and count to control the loop. Correct is initialised to 0 (false). It only becomes 1 (true) if the user guesses the number correctly. Count is initialised to 1. Each time the while loop runs count becomes 1 larger (count = count + 1). We say it is incremented. In this pseudocode we have a nested if selection inside of a while loop. while if if Each time the while loop runs the user enters a guess. This is then tested to see if it is correct or not. The loop will continue until either correct becomes true or count gets to 11. Prepare a program with effective internal documentation to go with this algorithm. Note: In some 3GLs you can declare correct as a Boolean variable, i.e. able to take values of true or false only. If running the pseudocode in the pseudocode compiler (see Appendix 3) there is no random function and so the first line will have to read something like number = 333. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  28. 28. Coding from algorithms 121 Definite iteration The loops we have looked at so far are described as indefinite. This means the steps in each loop are repeated until a certain condition was met. Depending on the variables involved the loop may run once, or many times, or not at all. The number of iterations is indefinite. Sometimes however we may know before we start exactly how many times a loop will run. For example say we wished to total takings from a store for each month over a year. In this case we know we want to repeat the steps that the loop will run twelve times. In this situation we have a case of definite iteration, we know before we start that the loop will run a definite number of times. The most common form of definite iteration is a do loop (or for loop in some 3GLs). The do loop can be below in both pseudocode and as an NS diagram: total = 0 do month = 1 to 12 prompt for takings get takings total = total + takings enddo write "The total for the year is $", total The pseudocode key words are do, to and enddo. There must be an ordinal (integer or char) type variable, called the loop counter, after do. This is followed by a range of values the loop counter will take. The lines in between the do and enddo are repeated the counted number of times. In the above algorithm (do month = 1 to 12 ...) the loop counter is the variable month. Each time the loop repeats the value in month increases by 1. The first time through month is 1, the next time through month is 2, and so on up to 12. To demonstrate a do loop in action we will use a trace table to follow the values in a sample pseudocode algorithm. do j = 1 to 4 one = j + j two = j * j three = 10 - j enddo Iteration j one two three 1 st 1 2 1 9 2 nd 2 4 4 8 3 rd 3 6 9 7 4 th 4 8 16 6 The loop iterates four times. Each time j takes on the next value, and the variables one, two and three reflect this. total = 0 do month = 1 to 12 prompt total = total + takings write total input takings © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  29. 29. Leading Technology 122 Activity 4.7 – Going loopy 1. Convert each of the following pseudocode segments into program steps in a 3GL with turn declared as an integer. Run each to see how the different do loops work. Alternatively these loops can be run in the pseudocode compiler (see Appendix 3). a do turn = 1 to 10 write "Go" enddo b do turn = 1 to 10 write turn enddo c do turn = 5 to 20 write turn enddo d do turn = 1 to 10 write turn * 5 enddo e start = 5; finish = 15; do turn = start to finish write turn enddo f do turn = 15 downto 5 write turn enddo g do turn = ‘a’ to ‘m’ write turn enddo h do j = 1 to 12 do k = 1 to 12 write j * k enddo enddo 2. What will be produced by each of these do loops? Do not convert these to a program; work out your answers on paper: a do j = 1 to 3 write "Hello" enddo b do j = 1 to 6 write j enddo c total = 0 do j = 1 to 5 total = total + 5 enddo write total Declare start and finish as integers Re-declare turn as a string/char These are nested loops, one is inside of another. They print out the 1 to 12 times multiplication tables. Declare j and k as integers. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  30. 30. Coding from algorithms 123 d total = 0 do j = 1 to 10 total = total + j enddo write total e start:= 5 finish = 10 do j = start to finish total = total + 5 enddo write total 3. a The following pseudocode totals the numbers from 1 to 100. total = 0 do count = 1 to 100 total = total + count enddo write total Convert the pseudocode into a 3GL. b Alter your program to permit the user to enter the beginning and end numbers and then total them. For example if the user enters 5 and 11, the program will output the sum of: 5+6+7+8+9+10+11. 4. The following pseudocode demonstrates how to select the largest of a group of input values. The user enters rainfall for each of the 12 months of the year and the program (through the variable max) records and outputs the largest value. Write the pseudocode as a 3GL program. max = 0 do month = 1 to 12 prompt for rainfall get rainfall if rainfall > max then max = rainfall endif enddo write "The maximum rainfall for the year was ", max 5. Prepare either the pseudocode to do the following:  enter the scores for a team of 11 cricketers  pick out the highest and lowest scores  calculate the average of all of the scores  display the highest, lowest, and average scores. Convert the pseudocode into an appropriately documented 3GL program. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  31. 31. Leading Technology 124 Subroutines In the last unit we saw that one step of an algorithm might be a call to another algorithm, i.e. one of the steps may be the name of a separate algorithm that will be carried out as part of the sequence of the main algorithm. In writing a computer program this called algorithm is written as a separate sub-program or subroutine. A subroutine is a named block of code that carries out an action, usually independent of the main program. Subroutines are a useful tool for breaking a program into modules, and are an important part of structured programming as we shall see shortly. Depending on the language used sub-programs may be called subroutines, subs, procedures, functions, or methods. These names may not mean the same thing in different languages, but in each case the sub-program is written separately from the main program and is called (or invoked) by the use of its name in the main program. The subroutine may be listed along with (either above or below) the main program, or may be contained in a library of subroutines that the main program has access to. For example the following function written in C: void addNumbers (int one, int two) { int total; total = one + two; printf ("%dn", total); } will add two numbers and output their total. The function is called in the main program: int main() { int first, second; first = 100; second = 350; addNumbers (first, second); exit(0); } The main program assigns values to first and second and then calls the addNumbers function. The variables first and second listed in brackets are called parameters, while the values in these parameters are called arguments. The arguments are said to be passed to the function. In the function these values are stored in the variables one and two until used. Note: The printf (print formatted) is also a function. It is used to output the result. In addition to being an important part of structured programming subroutines have two other advantages. Firstly a subroutine can be reused; once it is written it can be called again and again as needed by the main program. Secondly in using subroutines the main program is less cluttered and therefore easier to follow. Subroutine call in a Flowchart or NS diagram (a Redefined process) function call © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  32. 32. Coding from algorithms 125 Functions In addNumbers above the function does not pass a value back to the main program (hence the keyword void at the beginning). Some 3GLs however use subroutines that return a value to the calling program. These subroutines are usually called as part of an expression or assignment statement. For example in Delphi Pascal to store a random number between 0 and 999 in the variable guess we might use: guess := random(1000) ; or in Visual Basic to find the square root of the value in the variable number and store the answer in the variable Result: Result = Sqrt(Number) Again in each case the code for random or Sqrt is written elsewhere. The languages that use subroutines that can pass a value back to the main program, identify those subroutines as functions. These languages distinguish functions from procedures, which is what they call the subroutines that just carry out an action. Parameter passing The variables that hold values to be passed to a subroutine are called parameters. Parameters may be passed by value or by reference. If passed by value the calling variables are not affected; if passed by reference then the subroutine will change the calling variables. In the examples above the parameters are passed by value. The subroutines use the values passed to them, but nothing happens to the values in the original variables. On the other hand we sometimes want to change the calling variables, as in this Delphi Pascal example used to swap two values over: procedure swap (var one, two : integer); var temp : integer; begin temp := one; one := two; two := temp; end; If this was called with swap(first, second); the values in the original calling variables first and second would be swapped over. The parameters first and second have been passed to the procedure by reference. Whether a parameter is passed by value or reference is indicated in the way the sub-routine is written in each particular 3GL. (In the Delphi Pascal example above this is indicated by the presence or absence of var in the parameter brackets.) © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  33. 33. Leading Technology 126 Scope The scope of a variable is the parts of the program that are aware of its existence and can access values held by it. In the addNumbers example above, the variables one and two exist only within the function. They are not accessible by the rest of the program and when the function ends they cease to exist. They are described as having a local scope. This means they only exist for the part of the program immediately around them. Variables can have either a local, a unit/module wide, or a global scope. If a variable is declared as local it can be used only by the subroutine it is in. If a variable is declared as global, then it can be accessed by any part of the program; its scope is program-wide. (We will look at unit/module scope shortly.) To illustrate the difference between local and global scope say we had a program laid out like this: Any variable declared in the main program is available to be used in each of the subroutines A, B and C. This is a global variable. A variable declared in procedure A is available within the procedure, but cannot be accessed by any of the other subroutines, or the main program. This variable is local to procedure A. A variable declared in procedure B is available to both procedure B and function C, as C is a subroutine within B. Variables in B and C are not available to the main program or to procedure A. Variable scope If we want a variable to hold a general value that is available to all sections of a program we must declare it as global. On the other hand a variable declared in a procedure or function only exists within the bounds of that subroutine, and as such is called a local variable. In addition to local and global scope some programs use program blocks described as units or modules; these are virtually mini-programs within, or used by, the main program. Their purpose is to divide a large complex program into smaller, more manageable segments. Variables can be declared as local to their unit or module. This means they are available to any subroutine within the unit or module, but not to other parts of the main program outside of the unit or module, or to other units or modules. These variables have a unit/module-wide scope. Scope in action Local variables only exist within the procedure or function they are declared in. Any changes to the values in these variables has no effect outside of the subroutine. The rest of the program cannot access them or use the values stored in them. For example, the value held in a variable main proc B proc A func C © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  34. 34. Coding from algorithms 127 count declared in one subroutine is lost when that subroutine ends. If the subroutine is called again, or another subroutine uses a variable called count, the old value is no longer available. However what if we want to use our variable count in more than one subroutine? We might want to record how many times something happens in one place and then continue this count in another. If the variable has been declared as local then we are not able to retain the value from subroutine to subroutine. If we wish a subroutine to make a change to a variable that exists outside of the subroutine then that variable must be declared with a wider scope. Why not make all variables global? Well the wider the scope we give a variable the less control we have over it and the more chance for error there is, especially as programs get more complex. Local variables are useful for immediate calculations, and do not affect the rest of the program outside of their own immediate procedure or function. We should use them wherever possible. As a general rule it is best to give variables as little scope as possible, i.e. wherever possible use only local variables. A global variable that is available to many different procedures, units or modules might be affected in ways we are not immediately aware of. A change to a value in one part may ripple through to others and lead to unexpected consequences. This can make it very difficult to track down errors. In addition, one of the purposes of writing programs with subroutines or in modules is so that these are independent and portable. If a module depends on variables in other modules then we lose flexibility because we can only use the modules together. In summary:  use local variables that exist only within a given procedure or function wherever possible  use unit/module wide variables for values used by several procedures or functions in the unit or module  use global variables only for values that are required by all parts of the program, and only if there is no other alternative. As well as variables, constants also have scope and will only be recognised in the part of the program they are declared in. However, since the nature of a constant is to hold a universal or general value, it is a usual practice to include the declaration of constants with any global declaration. Recursion As stated in the last unit, any computer solvable problem can be written using a combination of sequence, selection and iteration. There is a variation of this theorem that substitutes recursion for iteration. A recursive algorithm or subroutine is one that calls itself. The logic of recursive algorithms can be difficult to follow, but they are interesting programming tools. They employ the passing of parameters to the procedure or function from within which the call is made. In effect the subroutine calls itself. At some point the calls must end, and at that point the calls return back up the path they have come down, to produce the desired result. (Recursion is a little like standing between two facing mirrors and seeing images of yourself repeated in each.) © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  35. 35. Leading Technology 128 Recursive subroutines work by calling themselves with a new set of values each time. In the following examples the variable in brackets holds an argument (value) that is passed to the procedure or function when it is called. Example 1 – a recursive algorithm to add a series of whole numbers from 1 to the number given: addition (number) if number is 1 then addition = 1 else addition = number + addition (number - 1) endif This would be called by a step such as addition (5) or result = addition(5). With a starting value of 5 this algorithm would perform the else part four times, each time calling the addition function with one less as argument each time. When the argument reached 1 the function would begin to step back out, adding the result of the previous function call to the total. Example 2 – a recursive algorithm to find the factorial of a given number. (The factorial of a number is the multiplication of the numbers less than or equal to it, e.g. the factorial of six is: 6! = 6 x 5 x 4 x 3 x 2 x 1 = 720): factorial (number) if number is 0 then factorial = 1 else factorial = number * factorial (number - 1) endif Example 3 – a recursive algorithm to find the power of a given number to a certain exponent, e.g. in 4 raised to the 3rd power, 43 = 64 , the 4 is the base and the 3 is the exponent: power (base, expon) if expon is 0 then power = 1 else power = base * power (base, expon - 1) endif In recursive functions each set of values is stored on a programming device called a stack. At some point there must be a stopping condition, otherwise the function will get caught in a loop that would be infinite. If the stack did not end, there would be an overflow error as the computer ran out of memory! The stack is a programming concept that can be visualised using the analogy of plate dispensers used in cafeterias. Such a dispenser holds a pile of plates sitting on a spring. Clean plates can be added by pushing the pile down, or plates needed for meals can be taken from the top of the dispenser. In just the same way arguments for recursive subroutines can be added or taken from the stack in a last in - first out (LIFO) sequence. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  36. 36. Coding from algorithms 129 Activity 4.8 – Functionality 1. a What is a subroutine? b Identify the forms of subroutine used in a 3GL you are familiar with? 2. For each of the listed functions determine the value returned if called with the parameters indicated. a The following Delphi function called by: answer := square(9); function Square(number:integer): integer; begin square := number * number; end; b The following VB function called by: Answer = Circumference(8) Function Circumference(Diameter As Integer) As Single Const Pi = 3.1415 Circumference := Pi * Diameter End Function c The following C function called by: answer = consumption(150, 6.5); float consumption (int distance, float petrol) { float total, rate; rate = distance / 100; total = petrol / rate; return(total); } d Using the following PHP function: <?php function total($one, $two, $three) { return ($one + $two + $three); } ?> i What would answer hold after the following call?: $answer = total ( 5, 8, 12); ii Why might the following not work as expected?: $answer = total ( 2.5, ‘a’, 3.8); 3. Write functions in a 3GL of your choice to: a Find half of a given value. b Find the area of a rectangle given length and breadth. c Find the hypotenuse of a right angled triangle given the other two sides. d Find the largest of three values. e Find the result when one value is raised to the power of the second (e.g. 34 = 81). (Hint: use a do or for loop.) f Find the factorial of a number (e.g. 5! is 5 x 4 x3 x2 x 1 = 120) 4. a Explain the difference between value and reference parameters. b If the 3GL you use supports passing parameters by value or reference, show how this distinction is made in a procedure or function definition. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  37. 37. Leading Technology 130 c Prepare a function with a reference parameter to cube a number e.g. cube(value) will convert value into value3 . 5. The following diagram shows the scope of functions in a procedure: procedure A; function X; function Y; function Z; begin : : end; a What are nested subroutines? b Which parts of the program can access variables in the following: i function X ii procedure A iii function Z. 6. a Explain the concept of a LIFO stack. b How do you think a FIFO queue might work? 7. Prepare a recursive function to double a variable a given number of times. For example double(3, 4) will return 24 (3 6 12 24). Challenge 1. Write a program or algorithm to calculate compound interest. It must accept the start year, the finish year and the rate of interest. The results should be printed out as a table showing a year by year analysis of principal, interest and amount. 2. Prepare a program that sets multiple choice questions before the user, and keeps track of performance. Features could include recording of statistics and a display of results. 3. Make a computerised battle ship game. 4. Create a game in which the user has to click on a randomly moving object. Keep a score for the user. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  38. 38. Coding from algorithms 131 SEI 4 – Software monopolies Currently Microsoft with its Windows operating system (OS) and Office suite of programs dominates the world of the business computer. While there are alternatives, the control Microsoft has on the market is a cause of concern to many. At the same time there are benefits to having programs that are so widely used. In this look at the social implications of programming we will investigate software monopolies. What is a monopoly? While many of us are familiar with the board game of Monopoly not everyone knows just what a true monopoly is, or how it affects us. A monopoly in the real world is the exclusive control of a commodity or service. This means one company or enterprise dominates the delivery of a product or activity so much that others find it difficult to compete. Examples of monopolies include the following:  electricity supply in many parts of Australia is limited to one provider  up to the 1980s IBM was the most dominant producer of computers with little competition from others; even though IBM introduced the first widely accepted PC, it has since lost its command of this industry  until recently Telstra was the only phone service provider in Australia; we now have competitors to Telstra for delivery of home, business and mobile phone services  in larger country towns there is often only one company that operates the bus service, one cinema, or one shop that supplies school uniforms  while not a complete monopoly the ubiquitous presence of Microsoft with Windows, Office, and Internet Explorer approaches the level of market domination. A commercial monopoly comes about when one company becomes so powerful it can either buy out its competitors or absorbs them into itself. Once a monopoly is established it is difficult for others to challenge it. This might be for a variety of reasons:  high sales lead to big profits; in turn these are reinvested in sales and marketing, or used to eliminate competition, so that they reinforce the dominance of the monopoly  there is a cost of development barrier in establishing a new product; only well financed companies have the resources to conduct extensive R&D; once costs are met further production is relatively cheap  in producing goods the more you make and sell, the cheaper you can do this; this is known as economy of scale and gives a significant advantage to larger enterprises  if users are familiar with your product it is difficult for competitors to get them to change; they have difficulty challenging the pre-existing user base  similarly there is a network effect where existing users who are familiar with the product influence new users and are able to assist with ideas and training; this encourages new users to go with the existing product; the network effect means that the more people who use a product, the more people will use the product! © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  39. 39. Leading Technology 132  the lock-in effect; once a technology, product or service is in use it is difficult and expensive to change to something new; not only does the new product have to be purchased and the old written off, but all users must be trained in the new product; this has a significant cost in time, money and efficiency. For all of these reasons once a monopoly is established it is difficult for others to compete with it. For better or worse There are some benefits of having a monopoly in place. Once there is a dominant product or service established it is possible to set consistent standards. As an example the Office suite of software has a reasonably consistent interface that makes the movement from one product to another simpler. The products are also compliant enough with each other so that they can share data and methods. Consistent standards lead to familiarity for users so that they do not have to learn a new way of working with each variation. In turn this makes for simplified training. Consistency is more efficient and cheaper for enterprises to deal with. With some forms of software so dominant in the marketplace it also means there are more related programs available. Programmers will develop applications for the dominant OS as it provides the biggest market. These third party developers sell more and this is therefore an incentive to produce more programs for this OS. In turn users will have a wider choice of applications. One example of this is the wide range of games available for the Windows OS, especially as compared to OSs such as Linux or Macintosh. While there are some advantages to standardisation, monopolies in general have a negative effect in society and on the marketplace. In particular monopolies tend to:  eliminate competition or restrain trade  reduce consumer choice  fix prices  limit innovation  subsidise losses  channel excess capital into other areas  give privileged access to subsidiaries  centralise power. The Microsoft monopoly Microsoft (MS) in its approach to market domination is a good example of some of these negative practices. Programs such as WordPerfect, Lotus 1-2-3, DBase and Netscape, once all market leaders, have been supplanted by Microsoft products. In turn companies with programs such as FoxBase and HotMail have been bought out, and their applications incorporated into the MS product line. By eliminating competition Microsoft has strengthened its market position. © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  40. 40. Coding from algorithms 133 This position however has come at the cost of limiting consumer choice. It is now difficult to buy a computer that does not come with Windows pre-installed. If the user wishes to use an alternative OS, net browser, email client, media player or instant messaging program the existing MS product must first be disabled or uninstalled. Since each of these is bound very closely to the Windows OS this can be difficult, or may have a significant effect on the way the computer operates. Despite having a major market share and significant profits, the prices for MS products are still high. Without effective competition there is little incentive for them to be lowered. There is also limited innovation in the MS product line. MS is known more for adopting and taking over products than for developing new ones of their own. The cost of this strategy is subsidised in the cost of software. The products that MS does develop have been released with numerous bugs and errors. Again with little opposition the need for a competitive level of quality is not as great. Microsoft has also been known to give privileged access to its own subsidiaries. Before new versions of software or Windows have been in general release MS has given sections of the company advanced access. This has given subsidiaries such as Excel a time advantage over rival products. With a high level of profitability MS has significant capital to re-invest. Some of this is used to limit competition, but the remainder can be used to expand into other areas – thus expanding the monopoly. The money can also be used to fund lobby groups and has led to a significant centralisation of power in the one entity. .net .net (dot-net) is Microsoft’s vision of the future of computing. It has been described as "Microsoft for the Internet" and involves much of the direction MS sees itself heading in. .net basically is a platform for XML web services so that applications can communicate and share data over the Internet. (XML is a refined form of HTML). Through .net a user will be able to run programs, not from within their computer, but over the Internet. Software would not be bought, but would be hired while being used. Data could also be stored on web servers so that it available everywhere and not just on one computer or intranet. To access these services users would need a subscription and pay a fee. The MSN passport is one step in the process to developing a subscription base for .net. While the service would have advantages for users there are concerns at permitting a commercial enterprise access to (and even control over) the data of others. Activity 4.9 – Fair trade? 1. a What is a monopoly? b Give three examples of your own of monopolies. 2. a List as many of the services as you can that Australia Post offers (not just letter delivery). © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12
  41. 41. Leading Technology 134 b Australia Post once was the sole provider of these services. Which of the services are now duplicated by other providers? c Is Australia Post a monopoly/ Say why or why not. 3. Once a monopoly is established it tends to stay in place. a Give three reasons why this might be so, explaining each. b Identify two advantages there are to having a monopoly in place. c Give four disadvantages of monopolies. d In what ways has Microsoft acted as a monopoly? 4. Discuss the potential effects of Microsoft’s .net approach. In your answer refer to both negative and positive effects. 5. Investigate the license agreement of a program such as HotMail. What control of personal information does the user have? 6. From the release of Windows XP Microsoft no longer accepts non-signed software to run under its OS. a Use an Internet search to find out what is meant by code signing and Microsoft’s Authenticode digital signature. Explain what each is. b What reasons does Microsoft give for introducing code signing? c Explain how the use of code signing could potentially be used to extend Microsoft’s control over software production, especially since XP rejects non-signed software. 7. a Identify as many Google applications as you can. b Why do you think Google was prepared to pay $US1.65 billion for YouTube? c In what way are Google’s activities monopolistic? Now we have the basics, let’s get onto real programming © Kevin Savage 2011 – Licensed to Hillcrest Christian College for use in 2011-12

×