Structured Programming Methods Chapter 1 - History of Programming PDF

Document Details

LuxuryHydrangea

Uploaded by LuxuryHydrangea

Daeyang University

Tags

programming languages computer programming programming history computer science

Summary

This document is a chapter on the history of programming languages from a textbook titled "Structured Programming Methods." The chapter explores various programming paradigms, including imperative, functional, logic, object-oriented, and declarative programming. It also discusses how algorithms and the development of programming languages are evaluated.

Full Transcript

Structured Programming Methods Chapter 1 – History of Programming 1 Objectives After completing this chapter you will be able to: x Describe the main advantages and disadvantages of each generation of language....

Structured Programming Methods Chapter 1 – History of Programming 1 Objectives After completing this chapter you will be able to: x Describe the main advantages and disadvantages of each generation of language. x Understand the reasons for their development. x Explain the differences between each generation of language. x Describe the basic concepts of object-oriented technology. x Explain how object-oriented programming differs from structured programming. 2 Introduction This chapter is intended to provide an overview for programming languages. It covers: x What is a programming language? x How programming languages have developed. x The language models. x Ways to evaluate their differences. x Programming from a chronological viewpoint. x An introduction to object-oriented concepts. Programming has developed gradually over the centuries, and there are several factors in human society that enabled programming to be developed. The roots of programming lie with the abacus and the development of our numbering system in India and the Arab world. What can be seen as the first programs were written for machinery such as looms and calculating machines during the Industrial Revolution of the 18/19th centuries. It has taken many centuries for programming languages to reach their current sophistication, and the chapter aims to explore that history. The final part of the chapter introduces object-orientation, a feature of very recent languages, in more detail. V1.0 1-3 1 / 89 Chapter 1 – History of Programming Structured Programming Methods 3 What is a Programming Language There are many definitions of what constitutes a programming language, and none of these is the ‘correct’ answer. What might have defined a programming language in the 19th century would not necessarily be detailed enough for a modern definition. This chapter aims to allow you to explore your own ideas of what you think a programming language might be. Programming languages are needed to allow human beings and computers to talk to each other. Computers, as yet, are unable to understand our everyday language or, in fact, the way we talk about the world. Computers understand logic expressed mathematically through what is known as machine code. Computer language consists of 1s and 0s or the binary system, which the majority of human beings would find very difficult to communicate in. Computer languages enable humans to write in a form that is more compatible with a human system of communication. This is then translated into a form that the computer can understand. Here are some different ideas on what constitutes a programming language. x A programming language has been defined as a tool to help the programmer. x A way of writing that can be read by both a human being and a machine. x A sequence of instructions for the machine to carry out. x A way for a human being to communicate with a machine that is unable to understand natural language. x A computer language offers a means of writing algorithms that can be understood by both human being and machine. Machines are unable to understand natural language, so a human being uses algorithms that are translated into machine code by the programming language. Machine code is difficult for humans to use, so a language ‘translates’ human readable language into machinereadable form. x A computer program offers humans a standard way of expressing algorithms to solve particular problems. As languages offer a convention it allows other humans to read the program, and change it if they need to. Exercise 1.1 [30 minutes] It is likely that there is no ‘correct’ way to define a programming language, but some examples are provided to compare with the ideas of the class. Form into small groups. Allow ten minutes for group discussion, and to produce a definition of a programming language. These definitions should then be presented to the class, and discussed as required.../ continued 1-4 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 2 / 89 Structured Programming Methods Chapter 1 – History of Programming Allow ten minutes for group discussion on the following points: x Are these examples saying the same thing as each other? x How are these definitions different? 4 Language Models There are currently several kinds of languages: x Imperative languages are formed from collections of basic commands, most often assignments and Input/Output (I/O), where the execution is sequenced by control structures (e.g. loops, conditionals, blocks). Imperative (or procedural) languages specify explicit sequences of steps to follow to produce a result. These languages include C, Pascal, Fortran and Assembly. x Functional languages are based on lambda-calculus from the 1930s. Programs consist of collections of function definitions and function applications. Higher order functions, abstract functions and lack of side effects might also be associated with functional programs. Examples include LISP, ‘pure’ Scheme, FP, ML and Haskell. Programs written in a functional language are generally compact and elegant, but have tended, until recently, to run slowly and require a lot of memory. x Logic programming consists of collections of statements within a particular logic. Most typically that logic is predicate logic. The original logic programming language was Prolog. x Object-oriented (OO) languages. Programs consist of objects that interact with each other. Some also associate inheritance and polymorphism with OO languages. Examples are Simula, Smalltalk-80, Eiffel and Java. x Declarative languages are collections of declarations. Many functional and logic languages are also declarative. You describe a pattern to be matched without writing the code to match the pattern. Some patterns would be difficult to write by hand. Declarative languages describe relationships between variables in terms of functions or inference rules and the language executor (interpreter or compiler) applies some fixed algorithm to these relations to produce a result. x Scripting languages work in conjunction with a larger application, support control of a variety of applications, are interpreted, or some combination thereof. x Parallel languages are collections of processes (or sometimes structured data) that communicate with each other; these include C* and Ada. V1.0 1-5 3 / 89 Chapter 1 – History of Programming Structured Programming Methods Definition: Algorithm A systematic procedure that produces  in a finite number of steps  the answer to a question or the solution of a problem. Definition: Lambda-calculus A system of mathematical logic Alonzo Church originated in the 1930s, which concerns the application of functions to their arguments. Lambda-calculus and its variations have been important in the development of computer programming languages. 5 Evaluating Languages Programming languages can be evaluated from a number of viewpoints, depending on either the programmer, the environment in which the programmer works or the standards of the organisation. When developing software, a programmer should consider which language is most suitable to the task, rather than relying on a language with which they are familiar. You wouldn’t want to use a spreadsheet to develop a database. All the features of the language need to be considered rather than just one particular feature. A wrong choice can mean that the software has to be re-written, which can be very frustrating and time- consuming. If you are going to develop a system it is important to choose your language according to the goals that you have in mind. For instance, you may want to teach object-oriented programming so you might choose Smalltalk, you might want to create interactive multimedia and use Java or business applications in COBOL. If you want to create a large-robust system you probably won’t want to use something that you normally to use for rapid development. There are a number of different ways that the programmer can think about the design of the system, from the top-down of structured programming to object- oriented design issues. Some languages are geared towards one particular style of design, whilst others incorporate many types. Each of these language paradigms enables the programmer to consider the problem from a different viewpoint. There are a few basic questions that can be asked to help when making these decisions: 1. How readable is the language, to humans? If parts of the program are going to be read or altered separately from the entire program is might be worth considering how legible they are going to be. It is also useful to consider the length of names allowed in the language, for instance an early form of Fortran allowed for only 6 characters. This can lead to clumsy abbreviations that are difficult to read. Statements such as GO TO, FOR, WHILE and LOOP have increased the readability of programs, and lead to neater programs. These statements also affect the syntax or grammar. 1-6 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 4 / 89 Structured Programming Methods Chapter 1 – History of Programming 2. When it comes to writing the program, how easy is it to write the program in this particular language? A programming language that is easy to write in can make the process easier and faster. It may help to reduce mistakes. FOR loops and other types of statement allow the programmer to write much simpler code. This will save time and money, and also make the program smaller. 3. How reliable is the language? Not all languages create robust programs, and some help the programmer to avoid making errors. A program that is not robust can cause errors, and code can ‘decay’. Any language that helps the programmer to avoid mistakes will make it easier to use. 4. How much would it cost to develop using a given language? Is the language expensive to use and to maintain? Programs may need to be updated or re- developed, and an expensive language may make this prohibitive. 5. How complicated is the syntax going to be? Syntax is an important consideration. Clarity and ease of understanding are important, as is a syntax that seems logical and sensible. Errors are very likely to occur where one area of syntax too closely resembles another, and the program may prove difficult to debug. Some theorists reason that if it is difficult to write a program to parse the language, then it follows that it will be problematical for the programmer to get it right. 6. Does the language have standards? Languages that have standards for writing programs have greater readability; for instance Java has standards for naming, commenting and capitalisation. Definition: Syntax The rules defining the legal sequences of symbolic elements in a language. The syntax rules define the form of various constructs in the language, but say nothing about the meaning of these constructs. Examples of constructs are: expressions, procedures, and programs (in the case of programming languages) and terms, well-formed formulas and sentences (in the case of logical languages). Exercise 1.2 [60 minutes] Algorithms, the lambda calculus and logic have all been influential in the development of programming languages. Search the web or find a book in your library that will show you some examples of algorithms in computing. You might find it helpful when looking online to use the keywords “algorithm + computing + introduction” or try typing “introduction to algorithms in computing”. You might find it helpful to look for examples of programming code that show how the program differs using different algorithms. Search for information on different types of languages to gain a better understanding of the main categories of language and what tasks they suit best. V1.0 1-7 5 / 89 Chapter 1 – History of Programming Structured Programming Methods Definition: Parsing The process of deciding whether a string of input symbols is a sentence of a given language and if so determining the syntactic structure of the string as defined by a grammar for the language. This is achieved by means of a program known as a parser or syntax analyser. Study Note Approaches accepted by the academic community and industry: FORTRAN is an early specialised language used by the science, mathematical and engineering communities both in academia and in industry. COBOL is still used in industry, and historically it has been the language of business and the mainframe. Artificial Intelligence (AI), Virtual Environments and Natural Language are being increasingly used. For example, a game was developed in the UK using AI characters that attracted attention from the army. The company was then requested to develop software for the army using the game as a basis. Pascal was developed as a teaching language, and is not viewed as a bona fide development language. With the increase in interest in object orientation, Pascal has declined as a teaching language and Smalltalk, or latterly Java, is often used as a teaching tool in its place. C++, Visual Basic, and Delphi are currently used as development languages in the UK, the latter two being RAD (Rapid Application Development) tools i.e. suited to quick prototyping and iterative development. Other visual languages include Visual J++, Visual C++ and Java Studio. The most common scripting languages used for web development are ActiveX (especially when related to plug-ins), JavaScript and VBScript. New developments such as Active Server Pages (ASP) can use any language so long as it is specified. When ASP was developed it was proprietary for the Windows Operating Systems and dependent on existing ownership of software, but otherwise essentially free for developers. ASP is now widely used and software has been developed to make it platform independent. Other database scripting languages include Cold Fusion, which is produced by the Allaire Corporation and a little more difficult to implement. Open source programming has grown with the growth of Linux. The Linux operating system is free and the code is available for other programmers. This concept of making code available to the programming community has spread to other programs such as Netscape. 1-8 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 6 / 89 Structured Programming Methods Chapter 1 – History of Programming 6 Chronology of Programming Computation has been in existence for a lot longer than the computer. Machines or devices were developed to either use these computations or for their calculation. Though these systems may seem primitive, modern computing still uses some of these early systems of computation. The complex systems of calculation often developed hundreds of years ago form the basis of modern computer languages. The earliest tool used by European society for computing numbers was the abacus. Arabs introduced the abacus into Europe around the year 1000AD, though the abacus itself was invented long before. Study note Until the adoption of the abacus arithmetic had been difficult to say the least. European numbers were still based on the Roman system of letters. The year 999AD was written as DCCCCLXXXXVIIIJ that became a simple M on the advent of the year 1000AD. 999 consisted of D (500) CCCC (400 or 4 lots of 100) L (50) XXXX (4 lots of 10) V (5) IIIJ or IIII (4). It would have been a difficult process indeed to add 999 and 999 together and it was even suggested at one point that 9000 should be the maximum number (MMMMMMMMM). With the abacus came not only a quick and easy means to make calculations, but also the zero and infinity. The abacus revolutionised arithmetic, and introduced two vital concepts that had been missing. The zero and infinity are vital to modern numerical disciplines, and to computer languages. A computer understands the world in terms of the binary system of numbering, in other words as a series of 1s and 0s. This would be impossible without the 0. The table in Appendix A shows a brief chronology of developments in computers and programming from prehistory to recent times. Developments in programming have also been dependent on the computer hardware itself. Until the invention of the PC, programmers expected to share time on a mainframe computer. The mainframe was generally a gigantic computer that was given a room to itself. Modern personal computers have allowed programmers to work on their own machines, whilst the development of networks has meant that sharing has become possible. V1.0 1-9 7 / 89 Chapter 1 – History of Programming Structured Programming Methods 7 The Language Generations The language generations span many decades, and begin with the development of machine code. Each generation adds new features and capabilities for the programmer to use. Languages are designed to create programs of a particular type, or to deal with particular problems. Modern languages have led to the development of completely different styles of programming involving the use of more human-like or natural language and re-usable pieces of code. This section aims to give you an introduction to the features of each language generation. Note that although it seems as if each generation supercedes the others, the ‘older’ languages are still very much in evidence. You will find many programs written in C and COBOL, and engineers frequently use FORTRAN. x The first generation of languages was machine language. Instructions and addresses were numerical. These programs were linked to the machine they were developed on. x The second generation allowed symbolic instructions and addresses. The program was translated by an assembler. Languages of this generation include IBM, BAL, and VAX Macro. These languages were still dependent on the machine they were developed on. x Third generation languages allowed the programmer to concentrate on the problem rather than the machine they were writing for. Other innovations included structured programming and database management systems. 3GL languages include FORTRAN, COBOL, Pascal, Ada, C, and BASIC. All 3GL languages are much easier for the human being to understand. x 4GL languages (fourth generation). These are known as non-procedural, they concentrate on what you want to do rather than how you are going to do it. 4GL languages include SQL, Postscript, and relational database orientated languages. x 5GL (fifth generation). These languages did not appear until the 1990s, and have primarily been concerned with Artificial Intelligence and Fuzzy Logic. The programs that have been developed in these languages have explored Natural Language (making the computer seem to communicate like a human being). 1-10 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 8 / 89 Structured Programming Methods Chapter 1 – History of Programming Study Note Structured programming was developed during the 1950s after Edgar Dijkstra’s insightful comments into the harmful nature of the GO TO statement. Dijkstra and others subsequently created a set of acceptable structures in programming that would enable development without GO TO statements. These structures produced programs that were easier to read by humans, easier to debug and easier to test. These structures have become some of the founding principles of modern programming methods. Although the principles of structured programming have had a profound effect on the programming world, it was not until the 1970s that an actual language was created for teaching structured programming. Pascal was developed especially for this purpose, though it is much derided as a toy language, and appears to have never been used in commercial development. It appears that existing languages such as COBOL and FORTRAN were changed to accommodate Dijkstra’s structures, or that programming included these structures through more indirect methods. Later generation languages such as C are fully-fledged structured programming languages; these are from the third generation and procedural, in that they are both written and executed step-by-step. C, in its turn, has formed the foundation for the object-oriented language C++. The three structures allowed in structured programming are sequence, selection, and iteration. Structures are also thought of in terms of substitution and combination, i.e. structures can be substituted or combined with other structures as long as the result equals a sequential structure. Structured programming also pays attention to design and testing with emphasis on a top- down approach. The top-down approach uses modularity as a means to ensure that the program is both legible and manageable, and also that these modules can be tested as they are developed. This is beneficial as it ensures that all modules should be tested and that bugs can be found in the modules that have most recently been added or altered. Structured programming also places emphasis on program documentation, which can be in the form of a chart or the structured coding/listing. This documentation allows for subsequent updating of modules, making these modules easier to locate in the program. Modularity also ensures greater opportunity for re-use of modules during development. Definition: Rapid Application Development A programming system that enables programmers to quickly build working programs. In general RAD systems provide a number of tools to help build graphical user interfaces that would normally take a large development effort. Two of the most popular RAD systems for Windows are Visual Basic and Delphi. V1.0 1-11 9 / 89 Chapter 1 – History of Programming Structured Programming Methods Study Note Areas of change since 1993. There have been a number of changes in the programming community since the early 90s. Perhaps the most widely publicised of these has been the development of Java. Other areas of innovation have been Rapid Application Development Packages such as Visual Basic and Borland Pascal. RAD applications have been heralded by their manufacturers as the solution to programming without programmers. Applications can be developed using a ‘visual’ or ‘drag and drop’ environment. Whilst it is the case that these programs do indeed speed up development, there are inherent problems with RAD that need to be considered during development. Emphasis on speed of development can mean that good design is neglected, and that the re-usability of components is not optimised. Time ‘saved’ during development, can lead to time lost after production as the application can become unmanageable and difficult to update. Other areas of change include: x Web-based mark-up languages such as Cold Fusion and Active Server Pages that interface with databases to provide dynamic web content. x A move towards distributed objects rather than the large mainframe applications of the past. x The emergence of ActiveX and Java applets – mini programs that run independently so can be used to customise and create interactive web sites. x Visual Basic being thoroughly integrated with Microsoft Office to customise programs. x During the 90s networks, TCL (Tool Command Language), PERL (Practical Extraction and Report Language), CGI (Common Gateway Interface) etc have all become common in industry. x ANSI (American National Standards Institute) standard for C++. Definition: TCL Short for Tool Command Language, and pronounced TCL or tickle, a powerful interpreted programming language developed by John Ousterhout. One of the main strengths of TCL is that it can be easily extended through the addition of custom TCL libraries. It is used for prototyping applications as well as for developing CGI scripts, though it is not as popular as PERL for the latter. 1-12 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 10 / 89 Structured Programming Methods Chapter 1 – History of Programming Definition: CGI Abbreviation of Common Gateway Interface, a specification for transferring information between a World Wide Web server and a CGI program. A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program could be written in any programming language including C, PERL , Java or Visual Basic. Definition: PERL Short for Practical Extraction and Report Language PERL is a programming language developed by Larry Wall especially designed for processing text. Because of its strong text processing abilities PERL has become one of the most popular languages for writing CGI scripts. PERL is an interpretive language that makes it easy to build and test simple programs. 8 Introduction to Object Oriented Concepts Programmers who undertake structured analysis, design and programming think about data items and how to manipulate and organise them. Object orientation offers a different way to think about software systems. The philosophy of object orientation proclaims that applications can be built by envisioning objects that work together. In theory this should be an easier way to develop programs because we live in a world made up of objects, know how they relate to one another, and ought to be able to transfer our understanding of these things to the equivalent in software terms. Object orientation allows a developer to construct systems based on the idea of components as opposed to the structures that form the basis of structured programming. This component based development lets objects be re-used or extended, reducing development time dramatically. Object oriented programming allows the following: x A system can be constructed from a set of objects  just as a house is built from bricks, windows and doors (amongst other things). x Adding new abilities to existing objects can expand a system  a door for a house might be a door to a room or a cupboard door, this door could be extended to include garage doors. x Creating new objects can expand a system; for example a house object may have stairs or a lift. No stairs might mean a bungalow, stairs would allow the house to have more than one floor, and a lift would allow a tall block of flats to be built. A house could be extended by including a conservatory. x The bricks, windows and door objects that were designed for the first house can also be used to build other houses. This reduces the development time, as the existing design can be used to create other objects. V1.0 1-13 11 / 89 Chapter 1 – History of Programming Structured Programming Methods The purpose of this introduction to object oriented programming is to encourage you to start thinking in terms of objects, as this approach is increasingly popular in general software development. 9 What is an Object  An introduction to Classes The world around us is full of objects and modern software aims to imitate the real world. Just like things in the real world, objects have state and behaviour. An object’s state can be thought of the things it knows; a car might have an engine type, a make, model number and a colour. The car’s behaviours are the things that it knows how to do, such as accelerating, braking, changing gear and turning the windscreen wipers on. The state for dog could be name, breed, colour, and hungry, and the dog can have behaviour such as snoring, barking, fetching and chasing cats. An object can be: 1. Some physical thing in the ‘real world’. 2. A representation of reality. 3. A tangible or visible thing. 4. A thing to which action or thought can be directed. 5. Passive  doing nothing until activated e.g. like a switch. 6. Active  continually monitoring until conditions change e.g. like a thermostat. An object is never: 1. A value (e.g. name). 2. A process (e.g. sort). 3. Time (e.g. 5 minutes). 1-14 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 12 / 89 Structured Programming Methods Chapter 1 – History of Programming 10 Classes An object is an instance, or example, of a category or class. The house system that was described earlier is a class or category, and the types of housing, e.g. apartment, bungalow are instances of that class. In the real world, we are instances of the people class, and we may also be instances of other classes such as the brother class, mother class, and student class. Software objects have state and behaviours; these form the structure of the object. The object’s state is made up of items of data called attributes (or properties) which describe aspects of the object, whilst its behaviours are the operations that the object carries out. Definition: Attribute An attribute is a property of class. It describes a range of values the property may hold in objects (that is instances) of that class. Every object of the class has a specific value for every attribute. Definition: Property Characteristic of an object. In many programming languages the term property is used to describe attributes associated with a data structure. Real world examples of object features are those that we might possess as a person. As instances of the person class, our attributes could be height, age, weight, nationality (note that the data for each of these attributes will be different in every case, because we as individuals are different) and our operations consist of eat, sleep, drink, go to college, do homework, play football, swim. A developer wishing to create a system that was based on people-related information that could be used for a marketing purpose might look at the following attributes and operations for the person class. Attributes might consist of age, name, address, telephone number, email address, income and operations include takes holidays, reads magazines, drinks alcohol, goes shopping, and drives cars. Classes have another advantage; they can be used as a template for creating other objects. The person class would give you a template for creating other instances of the person class. You have the template for creating a population. The computer class may have a series of attributes such as brand name, model name, size of hard drive, processor speed. The computer class operations might consist of play latest games, play CD-ROMS, send email, surf web, and play music. The computer class can act as a template for creating new instances of the class, i.e. new objects. V1.0 1-15 13 / 89 Chapter 1 – History of Programming Structured Programming Methods To put this more simply, the class can be thought of a mould for producing new objects. This ability to create new objects easily is an important aspect of object oriented software development. An object in the real world has many attributes and behaviours, and it follows that the more features that you include with your class the more it will reflect reality. For example, the games computer could include the following attributes in its specification: how many MBs memory, the type of graphics card, floppy disk and so forth. There are many other operations that the computer could perform from desktop publishing to recording music. 10.1 Classification Objects that share similarities and properties can be grouped together. Classification looks at the shared attributes and behaviours to create or describe classes of objects. A biologist studying a group of animals such as lizards, crocodiles, chameleons, turtles may decide that these belong to a class known as reptiles. These reptiles share behaviour such as cold-bloodedness and laying eggs and also data such as how big they are and what colour they are. Classes are defined by specifying data or attributes and behaviour (operations or methods). The data for an object can also be referred to as its variables, and its operations or methods are known as its responsibilities. There are a number of different terms for responsibilities, and they may be referred to as operations, methods or functions. The reptiles class defined the data and responsibilities for the class as follows: Reptiles Class Data Colour Size Responsibilities Laying eggs Rearing young Figure 1. 1 An Example of a Class Definition: Variable A unit of storage that can be modified during program execution usually by assignment or read operations. A variable is generally denoted by an identifier or by a name. In logic a variable is a name that can stand for any of an infinite set of values. 1-16 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 14 / 89 Structured Programming Methods Chapter 1 – History of Programming Responsibilities and data can be both stored in the class as a whole or for each instance of a class. The responsibilities or operations for the reptiles class could include the ability to grow. An instance of the reptiles class could grow to a particular size. Some instances of the reptiles class would be able to grow scales or be able to swim. The ability to move would be a class method, whilst the ability to swim would be an instance method. As a class people have eyes, but the colour of our eyes varies, so in any one instance, the colour of eyes is a variable. Likewise, a consumer class for marketing information might be as follows: x Class variables  total number of consumers interviewed. x Instance variables  address of particular consumer. Definition: Data Information, in any form, on which computer programs operate. The distinction between a program (instructions) and data is a fundamental one in computing. It is in this fundamental sense that the word is used in terms such as data bus, data cartridge and data protection. Data can be distinguished from graphics, text, and speech. Data is distinguished by the fact that it is organised in a structured, repetitive, and often compressed way. This definition of the term data relates closely with database, data independence, data model and data processing. Definition: Operations or methods Operations or methods in a programming language. Whatever is carried out by an operator or, more generally, anything that can take place within a program: a declaration, an assignment, a selection, a loop, the call of a function and so on. 10.2 Different Sorts of Classes There are two sorts of class that can be created, the abstract class and the concrete class. An abstract class may have one or more subclasses, but never an instance. In other words, an abstract class may be inherited by another class, but cannot become an instance of that class. A reptile is an abstract class, its data and responsibilities can be inherited, but a reptile is not an animal in its own right. A concrete class, however, is a class that can have one or more subclasses and/or instances. Instances of the reptile class such as lizard and crocodiles are concrete classes. They may have subclasses such as iguana and occur a number of times – have many instances. V1.0 1-17 15 / 89 Chapter 1 – History of Programming Structured Programming Methods Exercise 1.3 [60 minutes] Find a simple taxonomy for the animal kingdom. It can be any part of the classification that you are familiar with. For instance, you can look at cats as a group, with everything from lions and tigers to the domestic cat. Take a look at the animals that are grouped together. What attributes do they share? Are there any behaviours that are common to all of these animals? Are there any attributes that are specific to particular animals? Do these animals have special kinds of behaviour? List all the shared attributes and behaviours that the animals have. Next list the more specialised attributes and behaviours along with the animals or smaller groups of animals that they belong to. Exercise 1.4 [60 minutes] Find some specifications for computers produced by different manufacturers. These might be from company websites or computer magazines. Write a list of all the attributes common to these computers. 11 Encapsulation (or Information Hiding) and Abstraction Information hiding is an important concept in object-oriented systems, and takes place in two important ways. Firstly, information about objects is hidden from other objects by the system itself, this is known as encapsulation. Secondly, the developer can choose to hide information about a class or object to ‘streamline’ that object to suit their needs. This is known as abstraction. 11.1 Encapsulation Encapsulation can also be referred to as black box technology. Black box is usually used to refer to technology that shields the user from its mechanics or technological workings. Most modern electronic appliances hide their technological processes from users. Appliances such as televisions, radios and so forth hide how they show television and radio programmes, and all the user sees is those processes being carried out. Most television viewers or radio listeners are not interested in how their equipment works, merely that it does. With encapsulation an object bundles together its attributes (data) and its operations so that they are inseparable, they are part of the object. This information is hidden, hence information hiding, so that only the object knows about them and can act on them. 1-18 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 16 / 89 Structured Programming Methods Chapter 1 – History of Programming For instance, a computer knows what processor it is using and how efficiently it is running, but there is no direct way to find out. Another example might be that human beings know how hungry they are and how to eat, but there is no direct way to find out how hungry that person is or how their digestion system works. To find any of these things out, the object must be sent a message, just as a human being would be asked whether or not they are hungry. Encapsulation offers a distinct advantage to developers, as it reduces the potential for error. A broken object can affect the whole system, and if the software engineer needs to mend that object it may mean that the object can be repaired individually rather than repairing the whole system. In the real world, a television is usually linked to a video recorder, but they hide their operations from one another. If the television breaks down, it is only the television that needs repairing or replacing rather than the television, video and any other devices that might be attached. Encapsulation and information hiding mean that only an object can manipulate its data through using its own methods or operations. This prevents other objects from accessing its insides, and prevents accidents. A human digestive system knows about its data and operations, but does not make these available to the outside world. This prevents accidents happening to an important object in the human body. Although an object hides its operations from the outside world, it does allow a means of communicating with the outside world. This means of communicating is known as an interface. Interfaces are a feature of modern household items as well as encapsulation. Televisions and videos have remote controls to change channel and alter volume, microwaves have buttons or dials to set temperature and cooking duration, washing machines have dials to choose washing cycle. Computers communicate with users through an interface, for instance operating systems and other software packages that are being used. Exercise 1.5 [60 minutes] Find as many electronic objects in your house or classroom as you can. Alternatively, you can visit an electrical shop. These machines should all have some kind of interface for communicating with the outside world. What sorts of interface do these objects have? Do they differ according to the type of appliance, or are they part of the appliance’s design? Study some of the more familiar machines, or find some information about how they operate. What behaviours is the interface hiding? Is it useful to be able to hide these behaviours? Exercise 1.6 [30 minutes] Think about the interface to a washing machine. What features does that interface normally have? Write down a list of things in the interface. Now think about how the washing machine behaves. What operations does it hide from the person using the washing machine (encapsulate)? V1.0 1-19 17 / 89 Chapter 1 – History of Programming Structured Programming Methods 11.2 Abstraction Abstraction enables the developer to re-use a class, and filter out operations and attributes from that class that are superfluous to needs. An object may have a long list of associated features that are not always relevant to the system that the developer wishes to create. For instance, the marketing information class might provide extensive details of consumer lifestyles. A developer might decide to produce a system to sell information about pet-owning consumers to pet food manufacturers. The developer could choose to filter out operations such as the consumer’s favourite restaurants and hobbies, which newspapers they read and how many visits they make to the cinema. The pet food manufacturer may only be interested in where pet owners live, where they shop, do they travel by car, how many pets of what type and what brand of pet food they buy. The software developer may also need to create software that tracks the number of consumer profiles in each area in order to find which areas are under-represented. In this case, it may be the case that the detailed information recorded for each profile may be more than is needed for the system. Consumer spending habits could be left out, leaving just the basic demographic information for each consumer. This consumer profile can be filtered in any way to suit the software developer’s needs, and whatever the developer is left with after this process is an abstraction of the consumer profile. 12 Messages and Operations Objects communicate with each other by sending messages to one another. An object sends a message to another object telling it to perform an operation. This works in the same way as remote controls that send messages to objects such as televisions to tell them to perform operations such as change channel. The message itself only tells the object to perform the operation, not how to perform it. The object itself knows how to perform this operation from the class it belongs to. 12.1 Methods There is another fundamental difference between traditional programming and object orientation. Data traditionally had things done to it, whereas an object can do things. This ability to do things is called methods (or may be referred to as operations  not strictly accurate, but common practice). In programming terms, the difference would be Traditional data item: open (Door) Object: door open 1-20 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 18 / 89 Structured Programming Methods Chapter 1 – History of Programming An object’s methods are not necessarily available to all other objects in the system. Some methods can be accessed by outside objects and these are known as public methods. Other methods are only available by methods within the object itself, and these are known as private methods. In the real world, a computer would have some public methods that enable a human to interact with the system, such as open program and change screensaver. There are however, other methods that are available only to the computer itself, such as accessing the RAM. Exercise 1.7 [30 minutes] Open a program on your computer such as a word processing or drawing package. For instance, open a word processing package and think about what tasks you normally complete to produce a word-processed essay. Think about each button on the toolbar at the top of the program as an object. What operations can each button carry out? If you are not sure, open a new document or open an old one for editing. Make alterations to the text or add new content to the document. What is the button object doing to the document or selected part of the document? For example, the embolden button can make the text bold or can unembolden the text (return it to normal). Simple button objects for making text bold, italic or underlined. Dialogue box for formatting the fonts in your document. This box shows you the many operations that the box can perform. V1.0 1-21 19 / 89 Chapter 1 – History of Programming Structured Programming Methods Exercise 1.8 [30 minutes] Take a look at your computer and what messages you are sending it using your keyboard and mouse. Are there any that are the same? If the messages are the same, are they the same whether they are sent via the mouse or the keyboard? 12.2 Messages When an object receives a message from another object, it activates a method or operation. These messages are also known as requests or function calls. The television remote control sends a message to the television to perform an operation or activate a method such as change channel. This process of transmitting a message from the Message Sender to the Message Receiver is called message passing. The Message Sender does not know how the Message Receiver carries out this method as this information is hidden, hence the term information hiding. Messages may also contain arguments (parameters) to clarify the request. The television remote control will tell the television to change to a particular channel, to reduce the volume by one unit. A microwave can be asked to cook for a certain number of minutes, and a video to turn itself on at a particular time. 13 Relationships There are a number of relationships that objects can have with each other. Principal among these is inheritance and association. 13.1 Inheritance Classes are categories of objects, and an object is therefore an instance of a particular class. In providing a template for objects, a class also provides characteristics that are inherited by objects. A television object therefore inherits all the attributes and operations of the television class. Not only can an object inherit from its class, a class may also inherit from another class. This process is called inheritance. For example, a rice cooker, toaster, microwave and electric kettle are all classes in their own right, but each class is also a member of the kitchen appliances class. The kitchen appliance class is the parent or superclass of all the others, and these other classes inherit the characteristics of the kitchen appliance class; e.g., switch on, switch off, and buttons to turn the appliances operations on and off. The rice cooker, toaster, microwave and electric kettle are all therefore subclasses of the kitchen appliance class. Superclasses can also be thought of as a form of taxonomy, in the real world mammals share certain inherited characteristics such as bearing live young, being warm blooded and feeding milk to their offspring. Subclasses of the mammals superclass inherit these properties, as well as their own particular characteristics. 1-22 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 20 / 89 Structured Programming Methods Chapter 1 – History of Programming For instance, whales have fins and can swim underwater whereas cats have four legs and fur and usually remain on land. Definition: Taxonomy In a broad sense, the science of classification, but more strictly the classification of living and extinct organisms, i.e. biological classification. The term is derived from the Greek taxis. Exercise 1.9 [30 minutes] Consider the mammals superclass, and define some subclasses within that group. For instance, dogs and cats. What characteristics would these subclasses inherit? Exercise 1.10 [30 minutes] Get together with a friend or think about this on your own if you like. What characteristics do you share with other people in your group? You are going to develop the Student superclass. Write down the attributes and operations that you all share. Can you think of any subclasses for your student superclass? 13.2 Association Objects are often associated with each other, in the same way that people might be associated with each other in daily life. These object relationships can either be one-way or they can be two-way. Objects can also have relationships that are either one-to-one, they may be one-to-many or alternatively an object can have different relationships with the same object. These associations are known as multiplicity. A one-way or unidirectional relationship would exist between a human being and their television set. The human being can tell the television what operations to perform, but the television has no means to tell the human to perform operations. A two way or bi-directional relationship exists where two people are married. A person might be your friend and also your boss, that person is in a ‘is a friend of’ association as well as a ‘is the boss of’ association. A dog can be a pet as well as a guard dog, the dog is therefore in a ‘is the pet of’ association as well as a ‘is a guard dog for’ association. Classes can also associate with more than one class. A person can travel by boat and by aeroplane. The person class is therefore associated with both the boat and the aeroplane class. V1.0 1-23 21 / 89 Chapter 1 – History of Programming Structured Programming Methods 13.3 Multiplicity Multiplicity is a term that indicates the number of objects that are associated with one particular class. These associations can be one-to-one or one-to-many. For instance, a wife might have one husband; they have a one-to-one association. A mother, however, may have many children and she has a one-to-many association with those children. Multiplicity is very common in the real world; human beings walk on 2 legs (a one-to-two association), dogs walk on 4 legs (a one-to-four association), spiders walk on 8 and insects on 6. 14 Polymorphism Often developers will find that operations can have the same name even though they are associated with different objects. Polymorphism allows developers to re- use terminology and to allow it have more than one meaning. This can prove useful for a number of reasons. System modellers can talk to clients using terms that are familiar to them, and maintain client’s own terminology. Some operations fall naturally into certain terminology such as open and close, and it would be preferable to use words that have an obvious meaning. The ability to allow more than one meaning for each operation means that the developer can maintain terminologies without having to invent a new unique word every time a similar operation occurs. Polymorphism means that each object understands how it is supposed to perform an operation even though it may have the same name as another object’s operation. For instance, just as a human understands how different objects in the real world open, so each class in object orientation understands how that operation occurs. A human being performs the operation ‘open’ on many different items in every day life, from doors to boxes, books, bank accounts and conversations. These are all different types of operation, although they share the same name. Each class would understand how it is supposed to perform the operation ‘open’ in its own right. The term true polymorphism means that objects may share closely related method names. These polymorphic methods perform the same operation, but perhaps in a different way. Usually this stems from the object’s inheritance as the different class methods may be related by their superclass. 15 Summary In this chapter we have covered: x A general introduction to programming including the concept of a programming language. x A chronology of programming. x The idea of language generations. 1-24 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 22 / 89 Structured Programming Methods Chapter 1 – History of Programming x An introduction to structured programming. x An introduction to object-oriented concepts , such as:  Classes;  Encapsulation and information hiding;  Messages and operations;  Relationships;  Polymorphism. There are many languages and a number of different approaches. Structured programming brought a measure of order to what was previously a chaotic process. Now there is increasing emphasis on viewing software as objects, rather than concentrating on data. This is the reason for introducing object oriented concepts so early, but they will reappear throughout this workbook. 16 Self study Self Study 1 [60 minutes] 1. List the six key questions to ask when evaluating languages for use in a project. 2. What are the characteristics of each of the five generations of language? 3. How might we know whether a language fits into one generation rather than another? 4. What criteria do we use? 5. What was Dijkstra’s contribution to programming? 6. What was the main problem he was trying to overcome? 7. What was his solution? 8. What do we mean by structured programming? V1.0 1-25 23 / 89 Chapter 1 – History of Programming Structured Programming Methods Self Study 2 [60 minutes] 1. How does object orientation encourage you to think? 2. How is a system constructed? 3. How is a system expanded? 4. What are the supposed advantages of object oriented programming? 5. What is meant by state? 6. What is meant by behaviour of objects? 7. What is the general criteria for grouping objects? 8. What sorts of classification do you get? 9. What is the difference between an abstract and a concrete class? 10. What is meant by the term encapsulation? 11. Why is encapsulation important in the world of objects? 12. Describe the two different key sectors of relationships, inheritance and associations. 13. What are the differences? Get into the habit of thinking in classes. Look around you and categorise things. You will be meeting new words and new concepts. Back up these materials with further reading and thinking. It will take time to adjust. Self Study 3 [60 minutes] Look at the history of computing – key events table in Appendix A. Pick five events since 1960 and research them for further details. Find out more about the people and achievements involved, especially the problems they were trying to solve. How did their successes advance programming? 1-26 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 24 / 89 Structured Programming Methods Chapter 1 – History of Programming 17 Answers Answer 1.1 The definitions differ as the relationship between the writer and the program differs, for example: x Definition 1 is rather simplistic and does not explore what a programming language actually does to enable the human and the machine to communicate or how that process occurs. x Definition 2 shows that a programming language allows humans and computes to communicate but not how that takes place. x Definition 4 implies that humans use symbols and metaphor in their languages. Human language is mediated by the context of the speaker and the listener, and this is a very complex process. A computer does not understand these subtleties of human communication, and is only able to communicate on a very simple and prosaic level. Newer ‘natural’ computer languages and programming are being developed, but these are very complex and difficult to program. A computer is still only able to understand what it is told, or to process algorithms no matter how complex these might be. Answers 1.2 to 1. 5 are to research questions. Answer 1. 6 The washing machine interface may have buttons or dials that let you set the type of washing cycle that you want, wash a half load, spin clothes, set the temperature that you want to wash your clothes at. The machine also hides you from the individual prewashes, main cycle, rinses and spins in main wash cycles. Answer 1. 7 You can open and close windows or programs, open new programs, save and undo. These messages are all the same to the computer, it doesn’t care what you use to send them, because the message it receives is still the same. Answer 1.8 You will probably tell the computer to do operations such as open windows, programs, menus and email messages. Other operations are close, new and save. These operations might have the same name. V1.0 1-27 25 / 89 Chapter 1 – History of Programming Structured Programming Methods 1-28 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 26 / 89 Chapter 2 Variables, Control Structures and Calculations 1 Objectives................................................................................................................ 2-3 2 Introduction.............................................................................................................. 2-3 3 Variable Types and Names...................................................................................... 2-5 3.1 Variable Types.............................................................................................. 2-8 4 More Complex Calculations: the Order of Precedence......................................... 2-10 5 Control Structure 1  Sequence............................................................................. 2-13 6 Control Structure 2 – Selection.............................................................................. 2-13 The CASE Statement.................................................................................. 2-18 Solution to Exercise 2.8 using a CASE statement:..................................... 2-19 Logical operations....................................................................................... 2-19 PseudoCode solution................................................................................... 2-20 7 Control Structure 3 – Loops................................................................................... 2-22 7.1 WHILE a true condition occurs DO an action or block of actions............. 2-26 7.2 REPEAT an action or block of actions FOR a number of times................ 2-28 8 Summary................................................................................................................ 2-32 9 Self Study............................................................................................................... 2-33 9.1 Variables, Types and Names...................................................................... 2-33 9.2 Calculations and order of Precedence......................................................... 2-34 9.3 Control structure 1: sequence..................................................................... 2-34 9.4 Control structure 2: selection...................................................................... 2-35 9.5 Control Structure 3: Loops......................................................................... 2-37 10 Answers................................................................................................................. 2-40 10.1 Answers to self study exercises.................................................................. 2-48 V1.0 2-1 27 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods 2-2 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 28 / 89 Structured Programming Methods Chapter 2 – Variables, Control Structures and Calculations 1 Objectives At the end of this chapter you will be able to: x Understand the importance of the order of precedence. x Describe control structures. x Use calculations to construct computer programs. x Describe the different variable types and naming conventions. 2 Introduction Every programming language, like languages such as English, has rules which must be followed. The English language has words which must be used in a grammatical way to have meaning. For example the nouns computer, mouse, screen and data are nouns and click, enter and use are verbs. These are examples of the syntax of the language. The sentence “You can use the mouse to click on the screen to enter data into the computer” is meaningful. When learning the English language you might start with words such as nouns and verbs, moving on to adjectives and start to build phrases. Sentences are then developed, moving on to paragraphs where the sentences within the paragraph are of the same topic. It is easier for a student of English to write a paragraph than it is to write an essay or report. Definition: syntax (syntax rules) The rules defining the legal sequences of symbolic elements in a language. The syntax rules define the form of the various constructs in the language, but say nothing about the meaning of these constructs. Definition: language constructs A syntactic structure or set of structures in a language to express a particular class of operations. The term is often used as a synonym for control structure. We can relate a programming language to the English language. The building blocks are not nouns and verbs but reserved words and keywords which have a special meaning in the programming language. Examples of keywords are PRINT, INPUT and examples of reserved words are IF, REPEAT. Program statements or instructions are similar to sentences and procedures, functions and subroutines are similar to paragraphs in that they contain the instructions to perform a particular task. These terms will be addressed in more detail in chapter 4. V1.0 2-3 29 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods Since this workbook is concerned with concepts associated with programming rather than a particular programming language you will be using pseudocode throughout the workbook. Pseudocode is one of the tools that can be used to write a preliminary plan which can be developed into a computer program. It is not a standard language, although programmers often use terms within it that closely resemble the actual language to be used. Its purpose is to describe the algorithm (the method of solving the problem) in a form that can easily be understood and then translated into the actual programming code required. The syntax of the language to be used and the fine detail of the program are ignored until writing the source code, i.e. the program, which will be compiled (translated into binary digits that the computer can use) later. You will also be drawing diagrams to represent the algorithm. The diagrams are similar to flowcharting, although the official standards are not used. Flowcharting was used extensively in the 1960s before pseudocode and other charting techniques were available. The diagrams used have been chosen as compatible with more modern techniques of charting used later in the course for the object oriented programming languages. The first problem you will consider is to input three numbers from the keyboard of a personal computer, to add them together and to output the result. This can be thought of as a more general problem in that data is accepted, a process is performed on the data and the results are returned to the user or retained for use at a later stage. start input the numbers calculate the sum print the answer end Figure 2. 1 Solution in the form of a diagram The steps involved in solving this problem are shown in Figure 2.1. 2-4 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 30 / 89 Structured Programming Methods Chapter 2 – Variables, Control Structures and Calculations There must be a method of accepting data and storing it in the computers memory. The computer program also needs to know where the data is stored in memory so that it can process the data. Programming languages use variables for this purpose. 3 Variable Types and Names Variables are used to store data in the computer’s memory (RAM) during the time that the program is running. At this stage we will consider three attributes associated with variables. They are: x the address in memory where the data is stored; x the actual data stored which can change during the execution of the program; x the name of the variable or identifier. In the example to calculate the sum of three numbers you would need four variables. Programmers can choose the names of the variables, with certain limitations which we will address shortly. It is good practice to think of names which are meaningful in the context of the program, it will help you to understand the coding. In this case we could use number1, number2, number3 and sum. The pseudocode could be written as: ACCEPT number1, number2, number3 sum:= number1 + number2 + number3 PRINT sum end program When you declare number1 as a variable, an address in memory is allocated to it and the number input through the keyboard is stored in this memory location. Every time the identifier number1 is used in the program, this memory location would be accessed and thus the data stored in it can be read and manipulated. The programmer uses the identifier to gain access to the data, the generated program code deals with the connection between the variable and the memory location. It was mentioned earlier that there are certain limitations on the names you can use for variables. The name chosen must conform to certain rules so that the computer you are using to build your program does not receive ambiguous instructions. First, this means that you cannot use any of the words that make up the programming language. These words are called reserved words and have a special meaning in the programming language. All programming languages have a unique list of reserved words and you should make sure you are familiar with V1.0 2-5 31 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods the ones used in the programming language you will be learning. Punctuation marks and spaces may also have a special meaning within the grammar or syntax of the computer language you are learning, so these cannot be used as part of a variable name, either. You should make sure that you know how to create valid variable names in the programming language you will be using. In the pseudocode you have used so far, the words ACCEPT and PRINT can be thought of as reserve words. Identifiers are usually written as text although there are differences between programming languages in terms of the additional characters that can be used. In the pseudocode we will use the underline symbol to combine text to provide a meaningful name. E.g. average_student for the average mark for a student. In some languages this would be written as AverageStudent. Definition: pseudocode Another name for pseudolanguage. Definition: pseudolanguage Another name for pseudocode. A form of representation used to provide an outline description of the specification for a software module. Pseudolanguages contain a mixture of natural language expressions embedded in syntactic structures taken from programming language (such as IF … THEN …ELSE). The formality of the definition varies from ad hoc (e.g. defined within the project team) to being sufficiently formal to enable automatic parsing and syntax checking (e.g. supported by a CASE (Computer Aided Software Engineering) tool). Pseudolanguages are not intended to be executed by computer; they must be interpreted by people. Definition: variable 1. A unit of storage that can be modified during program execution, usually by assignment or read operations. A variable is generally denoted by an identifier or by a name. 2. The name that denotes a modifiable unit of storage. 2-6 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 32 / 89 Structured Programming Methods Chapter 2 – Variables, Control Structures and Calculations Definition: assignment statement A fundamental statement of all programming languages (except declarative languages) that assigns a new value to a variable. The typical form in Algol- like languages is variable:= expression where := is read as “becomes”; the symbol suggests a left-pointing arrow to signify the conveyance of a value to the variable on the left. Other languages (particularly BASIC, C and FORTRAN) use = as the assignment operator, e.g. a = b + c. This leads to problems in expressing the concept of equality. BASIC, being an unsophisticated language, is able to use = for both purposes; C uses = = for equality and FORTRAN uses EQ. Definition: identifier A string of characters used to identify (or name) some element of a program. The kind of element that can be named depends on the programming language; it may be a variable, a data structure, a procedure, a statement, a higher-level unit, or the program itself. Definition: name A notation for indicating an entity in a program or system. (The word can also be used as a verb.) The kinds of entity that can be named depend on the context, and include variables, data objects, functions, types, and procedures (in programming languages), nodes, stations, and processes (in a data communication network), files, directories, devices (in operating systems), etc. The name denotes the entity, independently of its physical location or address. Names are used for long-term stability (e.g. when specifying a node in a computer program) or for their ease of use by humans (who recognise the name more readily than an address). Names are converted to addresses by a process of name lookup. In many languages and systems, a name must be a simple identifier, usually a textual string. In more advanced languages, a name may be composed from several elementary components according to the rule of the language. V1.0 2-7 33 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods Definition: reserved word A word that has a specific role in the context in which it occurs, and therefore cannot be used for other purposes. For example, in many programming languages the words ‘IF’, ‘THEN’, ‘ELSE’ are used to organise the presentation of the written form of statements (between ‘THEN’ and ‘ELSE’ and following ‘ELSE’) whose execution is governed by the value of the Boolean expression between ‘IF’ and ‘THEN’. The use of IF, THEN or ELSE as identifiers is thus not permitted in these languages since they are reserved words. See also keyword. Definition: keyword A symbol in a programming language that has a special meaning for the compiler or interpreter. For example, keywords in BASIC include IF, THEN, PRINT. The keywords guide the analysis of the language, and in a simple language each keyword causes activation of a specific routine in the language processor. Definition: compiler A program that translates high-level language into absolute code, or sometimes into assembly language. The input to the compiler (the source code) is a description of an algorithm or program in a problem-oriented language; its output (the object code) is an equivalent description of the algorithm in a machine-oriented language. Definition: interpreter A language processor that analyses a line of code and then carries out the specified action, rather than producing a machine-code translation to be executed later. 3.1 Variable Types The compiler or interpreter needs to know what type of data is being used because it will have a different way of dealing with whole numbers, fractional numbers and characters. As you will see later, the type of data being used has a great influence on program design. 2-8 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 34 / 89 Structured Programming Methods Chapter 2 – Variables, Control Structures and Calculations The different types of data are represented as follows: Whole numbers (e.g. 1 678 45) Integer Fractional numbers (e.g. 3.678 789.3) Real or Float Letters (e.g. a f z 4) Character Names (e.g. Dr. H. Kelly ) String FALSE or TRUE, 0 OR 1 Boolean (only two values allowed) English postal codes contain letters, numbers and a space (which the computer treats as a blank character code rather than as an absent character) e.g. BD19 3FG. The computer would use this data as a string because it has a blank character in it. Numbers are only declared as integer or real if they are going to be used in calculations. Exercise 2.1 [45 minutes] Choose an appropriate data type for variables to be used in each of the following situations: a) For a metric measurement. b) To count a number of people. c) To calculate the total of a grocery bill. d) For a choice between 4 letters as in a multi-choice examination exercise. e) An international telephone number e.g. (01444) 123456. f) A catalogue code e.g. AZ1234. Many programming languages insist on a variables definition at the beginning of the program. This emphasizes the importance of data in deciding the structure of the program. It is good practice to identify the variables used and the types in the pseudocode. It is also good practice to describe any printed or displayed output, rather than just printing a number. You must remember that the output and input to the program are the human-computer interface and as such must be meaningful and helpful to the user. The pseudocode is now: Use variables: number1, number2, number3, sum OF TYPE Integer DISPLAY “Enter three numbers” ACCEPT number1, number2, number3 sum:= number1 + number2 + number3 PRINT “The sum is ” sum end program V1.0 2-9 35 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods Although variables are used to hold data which can change throughout the program, the data stored is always under the control of the program. Some variables may have data entered at the beginning of the program and the data stays the same throughout the running of the program (e.g. tax rate). You may wonder why a variable is used in this case, but consider the implications if a program performed calculations such as: tax_amount := price*17.5/100. The program code would have to be changed if the tax rate changed from 17.5%. Data items which have the same value throughout the program are termed constants. As with variables, the computer needs a name for each constant and to know its data type so that it can be manipulated as required during the program. Constants and variables obey the same rules and can be compared or used in arithmetic expressions provided they are of the same data type or of compatible types for the specific operation, e.g. integer and floating point. If 17.5 had been used in the above statement, we would call this a literal, not a constant. If a literal is other than a number; e.g. the heading of a report could contain “student name” and “grade”, then just as quotation marks have been used to help you distinguish the text as different to the words in the sentence, so must you enclose the text in quotation marks in the pseudocode. For example DISPLAY “Enter the student’s name”. Definition: constant 1. A quantity or data item whose value does not change. 2. A value that is determined by its denotation, i.e. a literal. Definition: literal A word or symbol in a program that stands for itself rather than as a name for something else, i.e. an object whose value is determined by its denotation. Numbers are literals; if other symbols are used as literals it is necessary to use some form of quoting mechanism to distinguish then from variables. 4 More Complex Calculations: the Order of Precedence In the pseudocode statement: sum := number1 + number2 + number3 a calculation is performed and the result assigned or copied into the location identified by the variable sum. Note that this means that the original data stored in the variable sum would be overwritten. 2-10 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 36 / 89 Structured Programming Methods Chapter 2 – Variables, Control Structures and Calculations Computer languages provide a range of operators for arithmetic. The signs that will be used in our pseudocode are: + meaning add – meaning subtract * meaning multiply / meaning divide For the moment, this is all we will use in our examples. The order in which a calculation is evaluated is very important since the end result can differ according to which operation is given precedence, i.e. performed before another. We shall do a simple example to illustrate the potential problem: The expression a:= 4 + 3*2 could be worked out in two different orders. 1) Add the 4 to the 3 and then multiply the result by 2 4+3=7 7*2=14 2) Multiply the 3 by the 2 and then add 4 to the result 3*2=6 6+4=10 One method of working has resulted in an answer of 14, the other an answer of 10. You may have encountered this problem during your early mathematics lessons. Having rules for the order of precedence of the arithmetic operations avoids this ambiguity. The way expressions are worked out by a computer are very similar to the rules in mathematics, and are: x do operations in brackets first; x then evaluate any exponentiation (e.g. finding the cube of a number, work out 6 to the power of 4); x then any multiplication or division operation; x and lastly addition and subtraction. Thus the correct answer for the expression a:= 4 + 3*2 is 10. If you wanted the addition to be performed first, you would have to write the expression as a:= (4 + 3)*2 and then the correct answer would be 14. Exercise 2.2 [15 minutes] Evaluate the following expressions to find the value assigned to a a) a:=6*3 + 2*(4+3) b) a:=3+5*(5-1) c) a:=3+2*(2-3) V1.0 2-11 37 / 89 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods Study Note When you are testing a program and having to work through the logic to try and find errors, you will need to be able to substitute data for variables in expressions to work out the current value of a variable. This is similar to algebra in Mathematics, but the data we use could be textual not just numbers. Consider a:=b2-4*c+d where b=2, c=3 and d=4 b2 = 2*2 = 4 4*c = 4*3 = 12 Now only add and subtract are left so a := 4  1

Use Quizgecko on...
Browser
Browser