Introduction to Programming PDF

Document Details

LuxuryHydrangea

Uploaded by LuxuryHydrangea

Daeyang University

2001

Roy Stepney, Sandra Powell, Geoff Henderson, Ann Jeffery

Tags

structured programming programming methods computer science introduction to programming

Summary

This workbook is focused on structured programming methods and various programming techniques. It aims to provide a thorough grounding in key concepts and skills related to programming's evolution into a more formalized process. Topics include programming language history, variables, control structures, data analysis, further programming techniques, object modeling, testing, and alternative methods. The book is not language-specific, emphasizing the development of transferable ideas and skills.

Full Transcript

Structured Programming Methods IDCS Structured Programming Methods Structured Programming Methods aims to give candidates a thorough grounding in the key concepts, techniques and methods to have emerged over time...

Structured Programming Methods IDCS Structured Programming Methods Structured Programming Methods aims to give candidates a thorough grounding in the key concepts, techniques and methods to have emerged over time as programming has evolved into a process with increasingly formalised approaches. This workbook focuses on the development of transferable ideas and skills and is not language specific. The topics covered include: History of Programming Languages Variables, Control Structures and Calculations Analysis of Data and Problems Further Programming Techniques Modelling Objects Testing Alternative Methods Implementation Structured Programming Methods Internet http://www.nccedu.com NCC Education Ltd is one of the world’s leading IT qualification- awarding bodies, with numerous academic and professional education and training courses being taught throughout the world. Our mission is to ensure the widespread availability of quality education and training for developers and users of IT. Structured Programming Methods NCC Education Limited Published by: NCC Education Limited The Towers, Towers Business Park Wilmslow Road, Didsbury Manchester M20 2EZ UK Tel: +44 (0) 161 438 6200 Fax: +44 (0) 161 438 6240 e-mail: [email protected] http://www.nccedu.com © NCC Education Limited, 2001 ISBN 1-90234-345-X The copyright in this document is vested in NCC Education Limited. The document must not be reproduced by any means, in whole or in part, or used for manufacturing purposes, except with the prior written permission of NCC Education Limited and then only on condition that this notice is included in any such reproduction. Information contained in this document is believed to be accurate at the time of publication, but no liability whatsoever can be accepted by NCC Education Limited arising out of any use made of this information. Roy Stepney, Sandra Powell, Geoff Henderson and Ann Jeffery assert the right to be identified as the authors of this workbook. First published 2001 Printed by B & Jo Enterprises PTE in Singapore Trademarks: NCC Education acknowledge that the trademarks and registered trademarks of products mentioned in this material are held by the companies producing them. Use of a term in this material should not be regarded as affecting the validity of any trademark or service mark. Copyright of any screen captures in this material are the property of the software’s manufacturer. This material may contain some clipart which is copyright to the Corel Corporation. The mention of any product in this workbook does not constitute an endorsement by NCC Education Limited. ii © NCC Education. All rights reserved. Unauthorised duplication is prohibited. NCC Education Portfolio Our portfolio includes comprehensive course packages, competence testing and accreditation services. We are also a publisher of academic textbooks. Academic Awards x ICCS - International Certificate in Computer Studies x IDCS - International Diploma in Computer Studies x IAD - International Advanced Diploma in Computer Studies x BCIS - BSc (Hons) in Computing and Information Systems x BCOL - BSc (Hons) in Computing - on line x MBIS - MSc in IT – Business Information Systems Professional Programmes x MSc in Professional Practice in IT x A+ x E-Commerce x PC Application Courseware x Visual Basic x JAVA Products x Student Materials supporting all NCC Education Courses x Tutor Training Materials to support our Courses x Euro PC Test – Automated Test Software for European Computer Driving Licence x PCDT – Automated Test Software for PC Driving Test Services x Course Accreditation x Centre Accreditation x Institute of IT Training – International Division V1.0 iii NCC Education NCC Education was originally the education division of the National Computing Centre. The National Computing Centre was set up by the UK government in 1966 to support and promote the use of computing technology within industry. As such, it developed strong links with the Information Technology (IT) industry. NCC Education Limited became a separate company in April 1997, since when we have introduced many more IT education programmes to our portfolio. Our mission is to ensure the widespread availability of quality education and training for developers and users of IT. Experts in our Field NCC Education is one of the world’s leading IT qualification awarding bodies, with numerous academic and professional educational and training courses being taught in over 30 countries. NCC Education’s specialists work with government and national bodies worldwide to devise and implement educational and training projects. NCC Education’s training programmes are recognised internationally as being an effective means for students to advance careers in IT. NCC Education provides comprehensive support from the outset, from the provision of comprehensive tutor and student training materials to moderating the process of training delivery and establishing the assessment mechanism. Who are our Partners? Our unique position bridging IT education and industry allows us to develop partnerships within many different types of organisation. In addition to our work with government and national bodies, our academic programmes are run in IT and business and colleges worldwide our professional programmes are run in colleges, large companies and IT training organisations worldwide. iv © NCC Education. All rights reserved. Unauthorised duplication is prohibited. International Diploma in Computer Studies IDCS is part of the NCC Education academic stream. IDCS is aimed at college leavers who wish to take either a stand-alone recognised qualification in information technology or the first step onto a degree programme. This diploma is also an ideal qualification for those professionals returning to college. IDCS gives students the ability to ‘pick and mix’ subjects, allowing them the freedom to explore the topics which will be of most benefit in developing their career. IDCS is a one year programme of full time study, comprising of four core modules, 4 elective modules and one practical project. Time is divided equally between lectures, practical exercises and self study. NCC Education carries out time constrained written examinations for the core modules, with the whole process managed from the United Kingdom. Accredited Centres hold responsibility for assessing the elective modules using clear instructions from NCC Education as to how the assessment is to be carried out. Assessment of each module may be by coursework, practical project, examination or a combination of each of these. IDCS is fully supported by lecturer notes and a student workbook supports each module. International Diploma in Computer Studies: COMPULSORY: Computer Technology Systems Development Business Organisation Business Communication MUST SELECT FOUR ELECTIVES: Computer Computer Internet and E-Commerce General Programming Technical Support Multimedia Structured A+ (PC Support Developing a E-Commerce Computerised Programming Methods Technician) Web Site Accounting (compulsory, within Developing a topic) Java, VB6 Networking Multimedia Web Site Practical Project V1.0 v ISO 9001 Quality in Education Historically, our aim has been to equip the UK with personnel who are competent in using and developing IT in business. As such, quality assurance is a rigorous requirement of all NCC Education products and partners. NCC Education has gained, and continuously maintained, a quality standard throughout the organisation. Its certificate number 928858/B was awarded by Lloyds’s Register Quality Assurance. The NCC Education Quality manual states: NCC Education is unreservedly committed to satisfying its customers through quality in all NCC Education’s products and services. In support of this policy, NCC Education operates a Quality System that provides a framework of standards and procedures within which it manages and controls all its project, product and service activities. The Quality System is based on the requirement of the pertinent parts of the ISO 9000 (BS 5750, EN 29000) Series, independently assessed for compliance to the appropriate standard. Specifically NCC Education’s quality objectives are: x To provide the highest quality administration and support to the international qualifications allied certification schemes. x To ensure that NCC Education accredited centres provide courses that meet the requirements specified in the NCC Education syllabus and regulations. x To specify and maintain syllabi and regulations that meet the career development needs of users and computer specialists in the IT community. x To ensure where appropriate that syllabi meet national academic standards.  vi © NCC Education. All rights reserved. Unauthorised duplication is prohibited. How to Use Your Workbook The author has been careful to structure this workbook with your assessment in mind. Each chapter therefore covers an essential part of the Structured Programming Methods Syllabus. This is a workbook, not a textbook and is aimed at providing an activity- based learning approach and is therefore extremely interactive. This workbook has a practical approach and is carefully structured to support and encourage you to discover and learn by doing. Your lecturer will allow you time during lectures to perform the various exercises contained in the Workbook. Generally, after each exercise carried out during class time, 5 or 10 minutes will be spent as lecturer led whole group feedback time. After the lecture on a particular chapter you should ensure that you carry out the self study exercise provided at the end of the chapter. This workbook should be used as an aid to the IDCS course Structured Programming Methods module. Throughout the workbook you will be given pointers to where you can get additional information if you should need it. This workbook is organised into eight subject-based chapters, each of which contain: Objectives These appear at the very beginning of each chapter and specify the topics and level of detail of the subject matter that you will be covering. Introduction Each chapter will always contain an introduction to the subject matter. Text Substantial text will follow regarding the subject matter, which will be interspersed with: x Exercises - These have been provided in order for you to test your knowledge of the subject matter. Questions have been carefully chosen to reinforce the course material. We have provided suggested answers to exercises at the end of each chapter - you should note that in some cases there are many potentially correct answers. V1.0 vii In order to gain the maximum benefit from each question we suggest that you attempt it to the best of your ability before you refer to the suggested answer. Some exercises may be in the form of actions to be carried out and have been provided to reinforce learning, confirm understanding and stimulate thought; there are no suggested answers. x Definition Statements – These statements define precisely the meaning of certain terms and the content in which they are used within the module. x Study Note - These are an aide-memoire and will help you to distinguish between text that is background knowledge and that which you should understand and be able to write about or carry out. You should pay close attention to these. They are there to ensure you are fully aware of any important points raised within the text. x Self Study Exercises – These are usually provided at the end of each chapter. This section of each chapter contains directed self study actions designed to enhance the learning experience and allow students to explore topics to a greater depth. Summary Finally, each chapter will end with a summary and will detail what you should understand and be able to write about or actions that you should be able to carry out. If you get to this stage and do not understand and/or cannot describe and explain the topics detailed in the summary, then we suggest you re-read the chapter, re-do any exercises/activities suggested and perhaps consider some further reading. Feedback Your feedback will help us improve our workbook. Should you have any questions regarding the content of this Workbook, or have any suggestions on how it could be improved, then please complete the feedback form at the back of this workbook. All that remains is for NCC Education to wish you all the very best on the course! viii © NCC Education. All rights reserved. Unauthorised duplication is prohibited. Workbook Contents (Note: A detailed Contents appears at the front of each chapter) Chapter 1 History of Programming Chapter 2 Variables, Control Structures and Calculations Chapter 3 Data Analysis and Problems Chapter 4 Further Programming Techniques Chapter 5 Modelling Objects Chapter 6 Testing Chapter 7 Alternative Methods Chapter 8 Implementation Appendix A History of Computing – Key Events Bibliography Glossary Index V1.0 ix x © NCC Education. All rights reserved. Unauthorised duplication is prohibited. Chapter 1 History of Programming 1 Objectives................................................................................................................ 1-3 2 Introduction.............................................................................................................. 1-3 3 What is a Programming Language........................................................................... 1-4 4 Language Models..................................................................................................... 1-5 5 Evaluating Languages.............................................................................................. 1-6 6 Chronology of Programming................................................................................... 1-9 7 The Language Generations.................................................................................... 1-10 8 Introduction to Object Oriented Concepts............................................................. 1-13 9 What is an Object  An introduction to Classes.................................................... 1-14 10 Classes................................................................................................................... 1-15 10.1 Classification.............................................................................................. 1-16 10.2 Different Sorts of Classes........................................................................... 1-17 11 Encapsulation (or Information Hiding) and Abstraction....................................... 1-18 11.1 Encapsulation.............................................................................................. 1-18 11.2 Abstraction.................................................................................................. 1-20 12 Messages and Operations....................................................................................... 1-20 12.1 Methods...................................................................................................... 1-20 12.2 Messages..................................................................................................... 1-22 13 Relationships.......................................................................................................... 1-22 13.1 Inheritance.................................................................................................. 1-22 13.2 Association.................................................................................................. 1-23 13.3 Multiplicity................................................................................................. 1-24 14 Polymorphism........................................................................................................ 1-24 15 Summary................................................................................................................ 1-24 16 Self study............................................................................................................... 1-25 17 Answers................................................................................................................. 1-27 V1.0 1-1 Chapter 1 – History of Programming Structured Programming Methods 1-2 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 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. 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 Chapter 1 – History of Programming Structured Programming Methods 1-28 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 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 Chapter 2 – Variables, Control Structures and Calculations Structured Programming Methods 2-2 © NCC Education. All rights reserved. Unauthorised duplication is prohibited. 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 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. 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 th

Use Quizgecko on...
Browser
Browser