Published on

Published in: Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Software Development Life Cycle (SDLC)Summary: As in any other engineering discipline, softwareengineering also has some structured models for softwaredevelopment. This document will provide you with ageneric overview about different software developmentmethodologies adopted by contemporary software firms.Read on to know more about the Software DevelopmentLife Cycle (SDLC) in detail.Curtain RaiserLike any other set of engineering products, software products are alsooriented towards the customer. It is either market driven or it drives themarket. Customer Satisfaction was the buzzword of the 80s. CustomerDelight is todays buzzword and Customer Ecstasy is the buzzword of thenew millennium. Products that are not customer or user friendly have noplace in the market although they are engineered using the besttechnology. The interface of the product is as crucial as the internaltechnology of the product.Market ResearchA market study is made to identify a potential customers need. This processis also known as market research. Here, the already existing need and thepossible and potential needs that are available in a segment of the societyare studied carefully. The market study is done based on a lot ofassumptions. Assumptions are the crucial factors in the development orinception of a products development. Unrealistic assumptions can cause anosedive in the entire venture. Though assumptions are abstract, thereshould be a move to develop tangible assumptions to come up with asuccessful product.Research and DevelopmentOnce the Market Research is carried out, the customers need is given tothe Research & Development division (R&D) to conceptualize a cost-effective system that could potentially solve the customers needs in amanner that is better than the one adopted by the competitors at present.Once the conceptual system is developed and tested in a hypotheticalenvironment, the development team takes control of it. The developmentteam adopts one of the software development methodologies that isgiven below, develops the proposed system, and gives it to the customer.The Sales & Marketing division starts selling the software to the availablecustomers and simultaneously works to develop a niche segment thatcould potentially buy the software. In addition, the division also passes thefeedback from the customers to the developers and the R&D division to
  2. 2. make possible value additions to the product.While developing a software, the company outsources the non-coreactivities to other companies who specialize in those activities. Thisaccelerates the software development process largely. Some companieswork on tie-ups to bring out a highly matured product in a short period.Popular Software Development ModelsThe following are some basic popular models that are adopted by manysoftware development firmsA. System Development Life Cycle (SDLC) ModelB. Prototyping ModelC. Rapid Application Development ModelD. Component Assembly ModelA. System Development Life Cycle (SDLC) ModelThis is also known as Classic Life Cycle Model (or) Linear Sequential Model(or) Waterfall Method. This model has the following activities.1. System/Information Engineering and ModelingAs software is always of a large system (or business), work begins byestablishing the requirements for all system elements and then allocatingsome subset of these requirements to software. This system view isessential when the software must interface with other elements such ashardware, people and other resources. System is the basic and very criticalrequirement for the existence of software in any entity. So if the system isnot in place, the system should be engineered and put in place. In somecases, to extract the maximum output, the system should be re-engineeredand spruced up. Once the ideal system is engineered or tuned, thedevelopment team studies the software requirement for the system.2. Software Requirement AnalysisThis process is also known as feasibility study. In this phase, thedevelopment team visits the customer and studies their system. Theyinvestigate the need for possible software automation in the given system.By the end of the feasibility study, the team furnishes a document that holdsthe different specific recommendations for the candidate system. It alsoincludes the personnel assignments, costs, project schedule, target datesetc.... The requirement gathering process is intensified and focussedspecially on software. To understand the nature of the program(s) to be built,the system engineer or "Analyst" must understand the information domainfor the software, as well as required function, behavior, performance andinterfacing. The essential purpose of this phase is to find the need and todefine the problem that needs to be solved .
  3. 3. 3. System Analysis and DesignIn this phase, the software development process, the softwares overallstructure and its nuances are defined. In terms of the client/servertechnology, the number of tiers needed for the package architecture, thedatabase design, the data structure design etc... are all defined in thisphase. A software development model is thus created. Analysis andDesign are very crucial in the whole development cycle. Any glitch in thedesign phase could be very expensive to solve in the later stage of thesoftware development. Much care is taken during this phase. The logicalsystem of the product is developed in this phase.4. Code GenerationThe design must be translated into a machine-readable form. The codegeneration step performs this task. If the design is performed in a detailedmanner, code generation can be accomplished without much complication.Programming tools like compilers, interpreters, debuggers etc... are usedto generate the code. Different high level programming languages like C, C++, Pascal, Java are used for coding. With respect to the type of application,the right programming language is chosen.5. TestingOnce the code is generated, the software program testing begins. Differenttesting methodologies are available to unravel the bugs that were committedduring the previous phases. Different testing tools and methodologies arealready available. Some companies build their own testing tools that aretailor made for their own development operations.6. MaintenanceThe software will definitely undergo change once it is delivered to thecustomer. There can be many reasons for this change to occur. Changecould happen because of some unexpected input values into the system. Inaddition, the changes in the system could directly affect the softwareoperations. The software should be developed to accommodate changesthat could happen during the post implementation period.Back to topB. Prototyping ModelThis is a cyclic version of the linear model. In this model, once therequirement analysis is done and the design for a prototype is made, thedevelopment process gets started. Once the prototype is created, it is givento the customer for evaluation. The customer tests the package and giveshis/her feed back to the developer who refines the product according to thecustomers exact expectation. After a finite number of iterations, the finalsoftware package is given to the customer. In this methodology, the softwareis evolved as a result of periodic shuttling of information between thecustomer and developer. This is the most popular development model in
  4. 4. the contemporary IT industry. Most of the successful software products havebeen developed using this model - as it is very difficult (even for a whiz kid!)to comprehend all the requirements of a customer in one shot. There aremany variations of this model skewed with respect to the projectmanagement styles of the companies. New versions of a software productevolve as a result of prototyping.Back to topC. Rapid Application Development (RAD) ModelThe RAD modelis a linear sequential software development process thatemphasizes an extremely short development cycle. The RAD model is a"high speed" adaptation of the linear sequential model in which rapiddevelopment is achieved by using a component-based constructionapproach. Used primarily for information systems applications, the RADapproach encompasses the following phases:1. Business modelingThe information flow among business functions is modeled in a way thatanswers the following questions:What information drives the business process?What information is generated?Who generates it?Where does the information go?Who processes it?2. Data modelingThe information flow defined as part of the business modeling phase isrefined into a set of data objects that are needed to support the business.The characteristic (called attributes) of each object is identified and therelationships between these objects are defined.3. Process modelingThe data objects defined in the data-modeling phase are transformed toachieve the information flow necessary to implement a business function.Processing the descriptions are created for adding, modifying, deleting, orretrieving a data object.4. Application generationThe RAD model assumes the use of the RAD tools like VB, VC++, Delphietc... rather than creating software using conventional third generationprogramming languages. The RAD model works to reuse existing programcomponents (when possible) or create reusable components (whennecessary). In all cases, automated tools are used to facilitate constructionof the software.
  5. 5. 5. Testing and turnoverSince the RAD process emphasizes reuse, many of the programcomponents have already been tested. This minimizes the testing anddevelopment time.Back to topD. Component Assembly ModelObject technologies provide the technical framework for a component-basedprocess model for software engineering. The object oriented paradigmemphasizes the creation of classes that encapsulate both data and thealgorithm that are used to manipulate the data. If properly designed andimplemented, object oriented classes are reusable across differentapplicationsand computer based system architectures. ComponentAssembly Model leads to software reusability. The integration/assembly ofthe already existing software components accelerate the developmentprocess. Nowadays many component libraries are available on the Internet.If the right components are chosen, the integration aspect is made muchsimpler.Back to topConclusionAll these different software development models have their own advantagesand disadvantages. Nevertheless, in the contemporary commercial softwareevelopment world, the fusion of all these methodologies is incorporated.Timing is very crucial in software development. If a delay happens in thedevelopment phase, the market could be taken over by the competitor. Alsoif a bug filled product is launched in a short period of time (quicker than thecompetitors), it may affect the reputation of the company. So, there shouldbe a tradeoff between the development time and the quality of the product.Customers dont expect a bug free product but they expect a user-friendlyproduct. That results in Customer Ecstasy!Systems Development Life CycleFrom Wikipedia, the free encyclopediaJump to: navigation, searchThis list may require cleanup to meet Wikipedias quality standards.Please help improve this list. It may be poorly defined, unverified or indiscriminate.This article or section is in need of attention from an expert on the subject.
  6. 6. Please help recruit one or improve this article yourself. See the talk page for details.Please consider using {{Expert-subject}} to associate this request with a WikiProjectSystems Development Life Cycle (SDLC) or sometimes just (SLC) is defined by theU.S. Department of Justice (DoJ) as a software development process, although it is also adistinct process independent of software or other information technology considerations.It is used by a systems analyst to develop an information system, including requirements,validation, training, and user ownership through investigation, analysis, design,implementation, and maintenance. SDLC is also known as information systemsdevelopment or application development. An SDLC should result in a high qualitysystem that meets or exceeds customer expectations, within time and cost estimates,works effectively and efficiently in the current and planned information technologyinfrastructure, and is cheap to maintain and cost-effective to enhance. SDLC is asystematic approach to problem solving and is composed of several phases, eachcomprised of multiple steps:• The Software concept - identifies and defines a need for the new system• A requirements analysis - analyzes the information needs of the end users• The architectural design - creates a blueprint for the design with the necessaryspecifications for the hardware, software, people and data resources• Coding and debugging - creates and programs the final system• System testing - evaluates the systems actual functionality in relation to expectedor intended functionality.1. Implementation2. Testing3. Evaluationor1. Feasibility Study2. Analysis3. Design4. Development5. Implementation6. Maintenanceor1. Feasibility Study2. Analysis3. Design4. Implementation5. Maintenanceor1. Feasibility Study2. Analysis3. Design4. Development5. Testing6. Implementation7. Maintenanceor1. Analysis(includingFeasibilityStudy)2. Design3. Development4. Implementation5. Evaluation or
  7. 7. 1. Feasibility Study2. Analysis3. Design4. Implementation5. Testing 6. Evaluation7. MaintenanceThe last row represents the most commonly used Life Cycle steps (used also in AQAmodule exams).Contents[hide]• 1 The Systems Life Cycle (UK Version)• 2 Systems Development Life Cycle: Building the Systemo 2.1 Insourcingo 2.2 Selfsourcingo 2.3 Prototypingo 2.4 Outsourcing• 3 References• 4 See also• 5 External links[edit] The Systems Life Cycle (UK Version)The SDLC is referred to as the Systems Life Cycle (SLC) in the United Kingdom,whereby the following names are used for each stage:1. Terms Of Reference — the management will decide what capabilities andobjectives they wish the new system to incorporate;2. Feasibility Study — asks whether the managements concept of their desired newsystem is actually an achievable, realistic goal, in-terms of money, time and endresult difference to the original system. Often, it may be decided to simply updatean existing system, rather than to completely replace one;3. Fact Finding and Recording — how is the current system used? Oftenquestionnaires are used here, but also just monitoring (watching) the staff to seehow they work is better, as people will often be reluctant to be entirely honestthrough embarrassment about the parts of the existing system they have troublewith and find difficult if merely asked;4. Analysis — free from any cost or unrealistic constraints, this stage lets minds runwild as wonder systems can be thought-up, though all must incorporateeverything asked for by the management in the Terms Of Reference section;5. Design — designers will produce one or more models of what they see a systemeventually looking like, with ideas from the analysis section either used ordiscarded. A document will be produced with a description of the system, but
  8. 8. nothing is specific — they might say touchscreen or GUI operating system, butnot mention any specific brands;6. System Specification — having generically decided on which software packagesto use and hardware to incorporate, you now have to be very specific, choosingexact models, brands and suppliers for each software application and hardwaredevice;7. Implementation and Review — set-up and install the new system (includingwriting any custom (bespoke) code required), train staff to use it and then monitorhow it operates for initial problems, and then regularly maintain thereafter.During this stage, any old system that was in-use will usually be discarded oncethe new one has proved it is reliable and as usable.8. Use - obviously the system needs to actually be used by somebody, otherwise theabove process would be completely useless.9. Close - the last step in a systems life cycle is its end, which is most oftenforgotten when you design the system. The system can be closed, it can bemigrated to another (more modern platform) or its data can be migrated into areplacing system.[edit] Systems Development Life Cycle: Building theSystemAll methods undertake the seven steps listed under insourcing to different degrees:[edit] InsourcingInsourcing is defined as having IT specialists within an organization to build theorganization’s system by• Planning – establishing the plans for creating an information system byo Defining the system to be developed – based on the systems prioritizedaccording to the organization’s critical success factor (CSF), a systemmust be identified and choseno the project scope – a high level of system requirements must be definedand put into a project scope documento Developing the project plan - – all details from tasks to be completed, whocompleted them and when they were completed must be formalizedo Managing and monitoring the project plan – this allows the organization tostay on track, creating project milestones and feature creeps which allowyou to add to the initial plan• Analysis – the users and IT specialists collaborate to collect, comprehend, andlogistically formalize business requirements byo Gathering the business requirements – IT specialists and knowledgeworkers collaborate in a joint application design (JAD) and discusswhich tasks to undertake to make the system most successful
  9. 9. o Analyzing the requirements – business requirements are prioritized andput in a requirements definition document where the knowledge workerwill approve and place their signatures• Design – this is where the technical blueprint of the system is created byo Designing the technical architecture – choosing amongst the architecturaldesigns of telecommunications, hardware and software that will best suitthe organization’s system and future needso Designing the systems model – graphically creating a model fromgraphical user interface (GUI), GUI screen design, and databases, toplacement of objects on screeno Write the test conditions - Work with the end users to develop the testscripts according to the system requirements• Development – executing the design into a physical system byo Building the technical architecture – purchasing the material needed tobuild the systemo Building the database and programs – the IT specialists write programswhich will be used on the system• Testing – testing the developed systemo Test the system using the established test scripts – test conditions areconducted by comparing expected outcomes to actual outcomes. If thesediffer, a bug is generated and a backtrack to the development stage mustoccur.• Deployment – the systems are placed and used in the actual workforce ando The user guide is createdo Training is provided to the users of the system - usually throughworkshops or online• Maintenance – keeping the system up to date with the changes in theorganization and ensuring it meets the goals of the organization byo Building a help desk to support the system users – having a team availableto aid technical difficulties and answer questionso Implementing changes to the system when necessary.[edit] SelfsourcingSelfsourcing is defined as having knowledge workers within an organization build theorganization’s system• Align selfsourcing applications to the goals of the organization – All intentionsmust be related to the organization’s goals and time management is key.• Establish what external assistance will be necessary – this may be where an ITspecialist in the organization may assist• Document and formalize the completed system created for future users –• Provide ongoing support - being able to maintain and make adjustments to thesystem as the environment changes..[edit] Prototyping
  10. 10. Prototyping is defined as creating a model, which displays the necessary characteristicsof a proposed system• Gathering requirements – these requirements will be stated by the knowledgeworkers as well as become apparent in comparison with the old or existing system• Create prototype of system – Confirm a technically proficient system by usingprototypes and create basic screen and reports• Review by knowledge workers - create a model of the system that will beanalyzed, inspected and evaluated by knowledge workers who will proposerecommendations to have the system reach its maximum potential• Revise the prototype – if necessary• Market the idea of the new system – use the prototype to sell the new system andconvince the organization of the advantages of switching up to the new system[edit] OutsourcingOutsourcing is defined as having a third party (outside the organization) to build theorganization’s system so expert minds can create the highest quality system by.• Outsourcing for development software -o Purchasing existing software and paying the publisher to make certainmodifications and paying the publisher for the right to make modificationsyourselfo Outsourcing the development of an entirely new unique system for whichno software exists• Selecting a target system – make sure there is no confidential information criticalto the organization that others should not see. If the organization is small enough,consider selfsourcing• Establish logical requirements - IT specialists and knowledge workers collaboratein a joint application design (JAD) and discuss which tasks to undertake to makethe system most successful to gather business requirements• Develop a request for a proposal – a request for proposal (RFP) is created andformalized. It includes everything the home organization is looking for in thesystem and can be used as the legal binding contract• Evaluate request for proposed returns and choose a vendor amongst the many whohave replied with different prototypes• Test and Accept a Solution – the chosen system must be tested by the homeorganization and a sign-off must be conducted• Monitor and Reevaluate – keep the system up to date with the changingenvironment and evaluate the chosen vendor’s ability and accommodate tomaintain the systemAlgorithm
  11. 11. In mathematics, computing, linguistics, and related disciplines, an algorithm is a definitelist of well-defined instructions for completing a task; that given an initial state, willproceed through a well-defined series of successive states, eventually terminating in anend-state. The transition from one state to the next is not necessarily deterministic; somealgorithms, known as probabilistic algorithms, incorporate randomness.The concept of an algorithm originated as a means of recording procedures for solvingmathematical problems such as finding the common divisor of two numbers ormultiplying two numbers. A partial formalization of the concept began with attempts tosolve the Entscheidungsproblem (the "decision problem") that David Hilbert posed in1928. Subsequent formalizations were framed as attempts to define "effectivecalculability" (cf Kleene 1943:274) or "effective method" (cf Rosser 1939:225); thoseformalizations included the Gödel-Herbrand-Kleene recursive functions of 1930, 1934and 1935, Alonzo Churchs lambda calculus of 1936, Emil Posts "Formulation I" of1936, and Alan Turings Turing machines of 1936-7 and 1939.Contents[hide]• 1 Etymology• 2 Why algorithms are necessary: an informal definition• 3 Formalization of algorithmso 3.1 Terminationo 3.2 Expressing algorithmso 3.3 Implementation• 4 Exampleo 4.1 Algorithm analysis• 5 Classeso 5.1 Classification by implementationo 5.2 Classification by design paradigmo 5.3 Classification by field of studyo 5.4 Classification by complexity• 6 Legal issues• 7 History: Development of the notion of "algorithm"o 7.1 Origin of the wordo 7.2 Discrete and distinguishable symbolso 7.3 Manipulation of symbols as "place holders" for numbers: algebrao 7.4 Mechanical contrivances with discrete stateso 7.5 Mathematics during the 1800s up to the mid-1900so 7.6 Emil Post (1936) and Alan Turing (1936-7, 1939)o 7.7 J. B. Rosser (1939) and S. C. Kleene (1943)o 7.8 History after 1950• 8 See also• 9 Notes• 10 References
  12. 12. o 10.1 Secondary references• 11 External links[edit] EtymologyAl-Khwārizmī, Persian astronomer and mathematician, wrote a treatise in Arabic in 825AD, On Calculation with Hindu Numerals. (See algorism). It was translated into Latin inthe 12th century as Algoritmi de numero Indorum,[1]which title was likely intended tomean "[Book by] Algoritmus on the numbers of the Indians", where "Algoritmi" was thetranslators rendition of the authors name in the genitive case; but peoplemisunderstanding the title treated Algoritmi as a Latin plural and this led to the word"algorithm" (Latin algorismus) coming to mean "calculation method". The intrusive "th"is most likely due to a false cognate with the Greek αριθμος (arithmos) meaning"number".Flowcharts are often used to graphically represent algorithms.[edit] Why algorithms are necessary: an informaldefinitionNo generally accepted formal definition of "algorithm" exists yet. We can, however,derive clues to the issues involved and an informal meaning of the word from thefollowing quotation from Boolos and Jeffrey (1974, 1999):"No human being can write fast enough, or long enough, or small enough to listall members of an enumerably infinite set by writing out their names, one afteranother, in some notation. But humans can do something equally useful, in thecase of certain enumerably infinite sets: They can give explicit instructions fordetermining the nth member of the set, for arbitrary finite n. Such instructionsare to be given quite explicitly, in a form in which they could be followed by acomputing machine, or by a human who is capable of carrying out only veryelementary operations on symbols" (boldface added, p. 19).The words "enumerably infinite" mean "countable using integers perhaps extending toinfinity". Thus Boolos and Jeffrey are saying that an algorithm implies instructions for aprocess that "creates" output integers from an arbitrary "input" integer or integers that, intheory, can be chosen from 0 to infinity. Thus we might expect an algorithm to be analgebraic equation such as y = m + n — two arbitrary "input variables" m and n thatproduce an output y. As we see in Algorithm characterizations — the word algorithmimplies much more than this, something on the order of (for our addition example):
  13. 13. Precise instructions (in language understood by "the computer") for a "fast,efficient, good" process that specifies the "moves" of "the computer" (machine orhuman, equipped with the necessary internally-contained information andcapabilities) to find, decode, and then munch arbitrary input integers/symbols mand n, symbols + and = ... and (reliably, correctly, "effectively") produce, in a"reasonable" time, output-integer y at a specified place and in a specified format.The concept of algorithm is also used to define the notion of decidability (logic). Thatnotion is central for explaining how formal systems come into being starting from a smallset of axioms and rules. In logic, the time that an algorithm requires to complete cannotbe measured, as it is not apparently related with our customary physical dimension. Fromsuch uncertainties, that characterize ongoing work, stems the unavailability of adefinition of algorithm that suits both concrete (in some sense) and abstract usage of theterm.For a detailed presentation of the various points of view around the definition of"algorithm" see Algorithm characterizations. For examples of simple additionalgorithms specified in the detailed manner described in Algorithmcharacterizations, see Algorithm examples.[edit] Formalization of algorithmsAlgorithms are essential to the way computers process information, because a computerprogram is essentially an algorithm that tells the computer what specific steps to perform(in what specific order) in order to carry out a specified task, such as calculatingemployees’ paychecks or printing students’ report cards. Thus, an algorithm can beconsidered to be any sequence of operations that can be performed by a Turing-completesystem. Authors who assert this thesis include Savage (1987) and Gurevich (2000):"...Turings informal argument in favor of his thesis justifies a stronger thesis:every algorithm can be simulated by a Turing machine" (Gurevich 2000:1)...according to Savage [1987], "an algorithm is a computational process definedby a Turing machine."(Gurevich 2000:3)Typically, when an algorithm is associated with processing information, data are readfrom an input source or device, written to an output sink or device, and/or stored forfurther processing. Stored data are regarded as part of the internal state of the entityperforming the algorithm. In practice, the state is stored in a data structure, but analgorithm requires the internal data only for specific operation sets called abstract datatypes.For any such computational process, the algorithm must be rigorously defined: specifiedin the way it applies in all possible circumstances that could arise. That is, anyconditional steps must be systematically dealt with, case-by-case; the criteria for eachcase must be clear (and computable).
  14. 14. Because an algorithm is a precise list of precise steps, the order of computation willalmost always be critical to the functioning of the algorithm. Instructions are usuallyassumed to be listed explicitly, and are described as starting "from the top" and going"down to the bottom", an idea that is described more formally by flow of control.So far, this discussion of the formalization of an algorithm has assumed the premises ofimperative programming. This is the most common conception, and it attempts todescribe a task in discrete, "mechanical" means. Unique to this conception of formalizedalgorithms is the assignment operation, setting the value of a variable. It derives from theintuition of "memory" as a scratchpad. There is an example below of such an assignment.For some alternate conceptions of what constitutes an algorithm see functionalprogramming and logic programming .[edit] TerminationSome writers restrict the definition of algorithm to procedures that eventually finish. Insuch a category Kleene places the "decision procedure or decision method or algorithmfor the question" (Kleene 1952:136). Others, including Kleene, include procedures thatcould run forever without stopping; such a procedure has been called a "computationalmethod" (Knuth 1997:5) or "calculation procedure or algorithm" (Kleene 1952:137);however, Kleene notes that such a method must eventually exhibit "some object" (Kleene1952:137).Minsky makes the pertinent observation, in regards to determining whether an algorithmwill eventually terminate (from a particular starting state):"But if the length of the process is not known in advance, then trying it may notbe decisive, because if the process does go on forever — then at no time will weever be sure of the answer" (Minsky 1967:105)As it happens, no other method can do any better, as was shown by Alan Turing with hiscelebrated result on the undecidability of the so-called halting problem. There is noalgorithmic procedure for determining of arbitrary algorithms whether or not theyterminate from given starting states. The analysis of algorithms for their likelihood oftermination is called termination analysis.In the case of non-halting computation method (calculation procedure) success can nolonger be defined in terms of halting with a meaningful output. Instead, terms of successthat allow for unbounded output sequences must be defined. For example, an algorithmthat verifies if there are more zeros than ones in an infinite random binary sequence mustrun forever to be effective. If it is implemented correctly, however, the algorithms outputwill be useful: for as long as it examines the sequence, the algorithm will give a positiveresponse while the number of examined zeros outnumber the ones, and a negativeresponse otherwise. Success for this algorithm could then be defined as eventuallyoutputting only positive responses if there are actually more zeros than ones in the
  15. 15. sequence, and in any other case outputting any mixture of positive and negativeresponses.See the examples of (im-)"proper" subtraction at partial function for more about what canhappen when an algorithm fails for certain of its input numbers — e.g., (i) non-termination, (ii) production of "junk" (output in the wrong format to be considered anumber) or no number(s) at all (halt ends the computation with no output), (iii) wrongnumber(s), or (iv) a combination of these. Kleene proposed that the production of "junk"or failure to produce a number is solved by having the algorithm detect these instancesand produce e.g., an error message (he suggested "0"), or preferably, force the algorithminto an endless loop (Kleene 1952:322). Davis does this to his subtraction algorithm —he fixes his algorithm in a second example so that it is proper subtraction (Davis1958:12-15). Along with the logical outcomes "true" and "false" Kleene also proposes theuse of a third logical symbol "u" — undecided (Kleene 1952:326) — thus an algorithmwill always produce something when confronted with a "proposition". The problem ofwrong answers must be solved with an independent "proof" of the algorithm e.g., usinginduction:"We normally require auxiliary evidence for this (that the algorithm correctlydefines a mu recursive function), e.g., in the form of an inductive proof that, foreach argument value, the computation terminates with a unique value" (Minsky1967:186)[edit] Expressing algorithmsAlgorithms can be expressed in many kinds of notation, including natural languages,pseudocode, flowcharts, and programming languages. Natural language expressions ofalgorithms tend to be verbose and ambiguous, and are rarely used for complex ortechnical algorithms. Pseudocode and flowcharts are structured ways to expressalgorithms that avoid many of the ambiguities common in natural language statements,while remaining independent of a particular implementation language. Programminglanguages are primarily intended for expressing algorithms in a form that can be executedby a computer, but are often used as a way to define or document algorithms.There is a wide variety of representations possible and one can express a given Turingmachine program as a sequence of machine tables (see more at finite state machine andstate transition table), as flowcharts (see more at state diagram), or as a form ofrudimentary machine code or assembly code called "sets of quadruples" (see more atTuring machine).Sometimes it is helpful in the description of an algorithm to supplement small "flowcharts" (state diagrams) with natural-language and/or arithmetic expressions writteninside "block diagrams" to summarize what the "flow charts" are accomplishing.Representations of algorithms are generally classed into three accepted levels of Turingmachine description (Sipser 2006:157):
  16. 16. • 1 High-level description:"...prose to describe an algorithm, ignoring the implementation details. At thislevel we do not need to mention how the machine manages its tape or head"• 2 Implementation description:"...prose used to define the way the Turing machine uses its head and the way thatit stores data on its tape. At this level we do not give details of states or transitionfunction"• 3 Formal description:Most detailed, "lowest level", gives the Turing machines "state table".For an example of the simple algorithm "Add m+n" described in all three levelssee Algorithm examples.[edit] ImplementationMost algorithms are intended to be implemented as computer programs. However,algorithms are also implemented by other means, such as in a biological neural network(for example, the human brain implementing arithmetic or an insect looking for food), inan electrical circuit, or in a mechanical device.[edit] ExampleOne of the simplest algorithms is to find the largest number in an (unsorted) list ofnumbers. The solution necessarily requires looking at every number in the list, but onlyonce at each. From this follows a simple algorithm, which can be stated in a high-leveldescription English prose, as:High-level description:1. Assume the first item is largest.2. Look at each of the remaining items in the list and if it is larger than the largestitem so far, make a note of it.3. The last noted item is the largest in the list when the process is complete.(Quasi-)formal description: Written in prose but much closer to the high-level languageof a computer program, the following is the more formal coding of the algorithm inpseudocode or pidgin code:Algorithm LargestNumberInput: A non-empty list of numbers L.Output: The largest number in the list L.largest ← L0for each item in the list L≥1, doif the item > largest, then
  17. 17. largest ← the itemreturn largest• "←" is a loose shorthand for "changes to". For instance, "largest ← item" means that the value oflargest changes to the value of item.• "return" terminates the algorithm and outputs the value that follows.For a more complex example of an algorithm, see Euclids algorithm for the greatestcommon divisor, one of the earliest algorithms known.[edit] Algorithm analysisAs it happens, it is important to know how much of a particular resource (such as time orstorage) is required for a given algorithm. Methods have been developed for the analysisof algorithms to obtain such quantitative answers; for example, the algorithm above has atime requirement of O(n), using the big O notation with n as the length of the list. At alltimes the algorithm only needs to remember two values: the largest number found so far,and its current position in the input list. Therefore it is said to have a space requirement ofO(1).[2](Note that the size of the inputs is not counted as space used by the algorithm.)Different algorithms may complete the same task with a different set of instructions inless or more time, space, or effort than others. For example, given two different recipesfor making potato salad, one may have peel the potato before boil the potato while theother presents the steps in the reverse order, yet they both call for these steps to berepeated for all potatoes and end when the potato salad is ready to be eaten.The analysis and study of algorithms is a discipline of computer science, and is oftenpracticed abstractly without the use of a specific programming language orimplementation. In this sense, algorithm analysis resembles other mathematicaldisciplines in that it focuses on the underlying properties of the algorithm and not on thespecifics of any particular implementation. Usually pseudocode is used for analysis as itis the simplest and most general representation.[edit] ClassesThere are various ways to classify algorithms, each with its own merits.[edit] Classification by implementationOne way to classify algorithms is by implementation means.• Recursion or iteration: A recursive algorithm is one that invokes (makesreference to) itself repeatedly until a certain condition matches, which is a methodcommon to functional programming. Iterative algorithms use repetitive constructslike loops and sometimes additional data structures like stacks to solve the givenproblems. Some problems are naturally suited for one implementation or theother. For example, towers of hanoi is well understood in recursive
  18. 18. implementation. Every recursive version has an equivalent (but possibly more orless complex) iterative version, and vice versa.• Logical: An algorithm may be viewed as controlled logical deduction. This notionmay be expressed as:Algorithm = logic + control.[3]The logic component expresses the axioms that may be used in the computationand the control component determines the way in which deduction is applied tothe axioms. This is the basis for the logic programming paradigm. In pure logicprogramming languages the control component is fixed and algorithms arespecified by supplying only the logic component. The appeal of this approach isthe elegant semantics: a change in the axioms has a well defined change in thealgorithm.• Serial or parallel or distributed: Algorithms are usually discussed with theassumption that computers execute one instruction of an algorithm at a time.Those computers are sometimes called serial computers. An algorithm designedfor such an environment is called a serial algorithm, as opposed to parallelalgorithms or distributed algorithms. Parallel algorithms take advantage ofcomputer architectures where several processors can work on a problem at thesame time, whereas distributed algorithms utilise multiple machines connectedwith a network. Parallel or distributed algorithms divide the problem into moresymmetrical or asymmetrical subproblems and collect the results back together.The resource consumption in such algorithms is not only processor cycles on eachprocessor but also the communication overhead between the processors. Sortingalgorithms can be parallelized efficiently, but their communication overhead isexpensive. Iterative algorithms are generally parallelizable. Some problems haveno parallel algorithms, and are called inherently serial problems.• Deterministic or non-deterministic: Deterministic algorithms solve the problemwith exact decision at every step of the algorithm whereas non-deterministicalgorithm solve problems via guessing although typical guesses are made moreaccurate through the use of heuristics.• Exact or approximate: While many algorithms reach an exact solution,approximation algorithms seek an approximation that is close to the true solution.Approximation may use either a deterministic or a random strategy. Suchalgorithms have practical value for many hard problems.[edit] Classification by design paradigmAnother way of classifying algorithms is by their design methodology or paradigm. Thereis a certain number of paradigms, each different from the other. Furthermore, each of
  19. 19. these categories will include many different types of algorithms. Some commonly foundparadigms include:• Divide and conquer. A divide and conquer algorithm repeatedly reduces aninstance of a problem to one or more smaller instances of the same problem(usually recursively), until the instances are small enough to solve easily. Onesuch example of divide and conquer is merge sorting. Sorting can be done on eachsegment of data after dividing data into segments and sorting of entire data can beobtained in conquer phase by merging them. A simpler variant of divide andconquer is called decrease and conquer algorithm, that solves an identicalsubproblem and uses the solution of this subproblem to solve the bigger problem.Divide and conquer divides the problem into multiple subproblems and soconquer stage will be more complex than decrease and conquer algorithms. Anexample of decrease and conquer algorithm is binary search algorithm.• Dynamic programming. When a problem shows optimal substructure, meaningthe optimal solution to a problem can be constructed from optimal solutions tosubproblems, and overlapping subproblems, meaning the same subproblems areused to solve many different problem instances, a quicker approach calleddynamic programming avoids recomputing solutions that have already beencomputed. For example, the shortest path to a goal from a vertex in a weightedgraph can be found by using the shortest path to the goal from all adjacentvertices. Dynamic programming and memoization go together. The maindifference between dynamic programming and divide and conquer is thatsubproblems are more or less independent in divide and conquer, whereassubproblems overlap in dynamic programming. The difference between dynamicprogramming and straightforward recursion is in caching or memoization ofrecursive calls. When subproblems are independent and there is no repetition,memoization does not help; hence dynamic programming is not a solution for allcomplex problems. By using memoization or maintaining a table of subproblemsalready solved, dynamic programming reduces the exponential nature of manyproblems to polynomial complexity.• The greedy method. A greedy algorithm is similar to a dynamic programmingalgorithm, but the difference is that solutions to the subproblems do not have to beknown at each stage; instead a "greedy" choice can be made of what looks best forthe moment. The greedy method extends the solution with the best possibledecision (not all feasible decisions) at an algorithmic stage based on the currentlocal optimum and the best decision (not all possible decisions) made in previousstage. It is not exhaustive, and does not give accurate answer to many problems.But when it works, it will be the fastest method. The most popular greedyalgorithm is finding the minimal spanning tree as given by Kruskal.• Linear programming. When solving a problem using linear programming,specific inequalities involving the inputs are found and then an attempt is made tomaximize (or minimize) some linear function of the inputs. Many problems (suchas the maximum flow for directed graphs) can be stated in a linear programmingway, and then be solved by a generic algorithm such as the simplex algorithm. A
  20. 20. more complex variant of linear programming is called integer programming,where the solution space is restricted to the integers.• Reduction. This technique involves solving a difficult problem by transforming itinto a better known problem for which we have (hopefully) asymptoticallyoptimal algorithms. The goal is to find a reducing algorithm whose complexity isnot dominated by the resulting reduced algorithms. For example, one selectionalgorithm for finding the median in an unsorted list involves first sorting the list(the expensive portion) and then pulling out the middle element in the sorted list(the cheap portion). This technique is also known as transform and conquer.• Search and enumeration. Many problems (such as playing chess) can bemodeled as problems on graphs. A graph exploration algorithm specifies rules formoving around a graph and is useful for such problems. This category alsoincludes search algorithms, branch and bound enumeration and backtracking.• The probabilistic and heuristic paradigm. Algorithms belonging to this class fitthe definition of an algorithm more loosely.1. Probabilistic algorithms are those that make some choices randomly (or pseudo-randomly); for some problems, it can in fact be proven that the fastest solutionsmust involve some randomness.2. Genetic algorithms attempt to find solutions to problems by mimicking biologicalevolutionary processes, with a cycle of random mutations yielding successivegenerations of "solutions". Thus, they emulate reproduction and "survival of thefittest". In genetic programming, this approach is extended to algorithms, byregarding the algorithm itself as a "solution" to a problem.3. Heuristic algorithms, whose general purpose is not to find an optimal solution, butan approximate solution where the time or resources are limited. They are notpractical to find perfect solutions. An example of this would be local search, tabusearch, or simulated annealing algorithms, a class of heuristic probabilisticalgorithms that vary the solution of a problem by a random amount. The name"simulated annealing" alludes to the metallurgic term meaning the heating andcooling of metal to achieve freedom from defects. The purpose of the randomvariance is to find close to globally optimal solutions rather than simply locallyoptimal ones, the idea being that the random element will be decreased as thealgorithm settles down to a solution.[edit] Classification by field of studySee also: List of algorithmsEvery field of science has its own problems and needs efficient algorithms. Relatedproblems in one field are often studied together. Some example classes are searchalgorithms, sorting algorithms, merge algorithms, numerical algorithms, graphalgorithms, string algorithms, computational geometric algorithms, combinatorialalgorithms, machine learning, cryptography, data compression algorithms and parsingtechniques.
  21. 21. Fields tend to overlap with each other, and algorithm advances in one field may improvethose of other, sometimes completely unrelated, fields. For example, dynamicprogramming was originally invented for optimization of resource consumption inindustry, but is now used in solving a broad range of problems in many fields.[edit] Classification by complexitySee also: Complexity classAlgorithms can be classified by the amount of time they need to complete compared totheir input size. There is a wide variety: some algorithms complete in linear time relativeto input size, some do so in an exponential amount of time or even worse, and somenever halt. Additionally, some problems may have multiple algorithms of differingcomplexity, while other problems might have no algorithms or no known efficientalgorithms. There are also mappings from some problems to other problems. Owing tothis, it was found to be more suitable to classify the problems themselves instead of thealgorithms into equivalence classes based on the complexity of the best possiblealgorithms for them.[edit] Legal issuesSee also: Software patents for a general overview of the patentability of software,including computer-implemented algorithms.Algorithms, by themselves, are not usually patentable. In the United States, a claimconsisting solely of simple manipulations of abstract concepts, numbers, or signals do notconstitute "processes" (USPTO 2006) and hence algorithms are not patentable (as inGottschalk v. Benson). However, practical applications of algorithms are sometimespatentable. For example, in Diamond v. Diehr, the application of a simple feedbackalgorithm to aid in the curing of synthetic rubber was deemed patentable. The patentingof software is highly controversial, and there are highly criticized patents involvingalgorithms, especially data compression algorithms, such as Unisys LZW patent.Additionally, some cryptographic algorithms have export restrictions (see export ofcryptography).This short section requires expansion.[edit] History: Development of the notion of"algorithm"[edit] Origin of the wordSee also: Timeline of algorithms
  22. 22. The word algorithm comes from the name of the 9th century Persian mathematician AbuAbdullah Muhammad ibn Musa al-Khwarizmi whose works introduced Indian numeralsand algebraic concepts. He worked in Baghdad at the time when it was the centre ofscientific studies and trade. The word algorism originally referred only to the rules ofperforming arithmetic using Arabic numerals but evolved via European Latin translationof al-Khwarizmis name into algorithm by the 18th century. The word evolved to includeall definite procedures for solving problems or performing tasks.[edit] Discrete and distinguishable symbolsTally-marks: To keep track of their flocks, their sacks of grain and their money theancients used tallying: accumulating stones or marks scratched on sticks, or makingdiscrete symbols in clay. Through the Babylonian and Egyptian use of marks andsymbols, eventually Roman numerals and the abacus evolved. (Dilson, p.16–41) Tallymarks appear prominently in unary numeral system arithmetic used in Turing machineand Post-Turing machine computations.[edit] Manipulation of symbols as "place holders" for numbers: algebraThe work of the ancient Greek geometers, Persian mathematician Al-Khwarizmi (oftenconsidered as the "father of algebra"), and Western European mathematicians culminatedin Leibnizs notion of the calculus ratiocinator (ca 1680):"A good century and a half ahead of his time, Leibniz proposed an algebra oflogic, an algebra that would specify the rules for manipulating logical concepts inthe manner that ordinary algebra specifies the rules for manipulating numbers"(Davis 2000:18).[edit] Mechanical contrivances with discrete statesThe clock: Bolter credits the invention of the weight-driven clock as “The key invention[of Europe in the Middle Ages]", in particular the verge escapement (Bolter 1984:24) thatprovides us with the tick and tock of a mechanical clock. “The accurate automaticmachine” (Bolter 1984:26) led immediately to "mechanical automata" beginning in thethirteenth century and finally to “computational machines" – the difference engine andanalytical engines of Charles Babbage and Countess Ada Lovelace (Bolter p.33–34,p.204–206).Jacquard loom, Hollerith punch cards, telegraphy and telephony — theelectromechanical relay: Bell and Newell (1971) indicate that the Jacquard loom (1801),precursor to Hollerith cards (punch cards, 1887), and “telephone switching technologies”were the roots of a tree leading to the development of the first computers (Bell andNewell diagram p. 39, cf Davis (2000)). By the mid-1800s the telegraph, the precursor ofthe telephone, was in use throughout the world, its discrete and distinguishable encodingof letters as “dots and dashes” a common sound. By the late 1800s the ticker tape (ca
  23. 23. 1870s) was in use, as was the use of Hollerith cards in the 1890 U.S. census. Then camethe Teletype (ca 1910) with its punched-paper use of Baudot code on tape.Telephone-switching networks of electromechanical relays (invented 1835) was behindthe work of George Stibitz (1937), the inventor of the digital adding device. As heworked in Bell Laboratories, he observed the “burdensome’ use of mechanical calculatorswith gears. "He went home one evening in 1937 intending to test his idea.... When thetinkering was over, Stibitz had constructed a binary adding device" (Valley News, p. 13).Davis (2000) observes the particular importance of the electromechanical relay (with itstwo "binary states" open and closed):It was only with the development, beginning in the 1930s, of electromechanicalcalculators using electrical relays, that machines were built having the scopeBabbage had envisioned." (Davis, p. 148)[edit] Mathematics during the 1800s up to the mid-1900sSymbols and rules: In rapid succession the mathematics of George Boole (1847, 1854),Gottlob Frege (1879), and Giuseppe Peano (1888–1889) reduced arithmetic to a sequenceof symbols manipulated by rules. Peanos The principles of arithmetic, presented by anew method (1888) was "the first attempt at an axiomatization of mathematics in asymbolic language" (van Heijenoort:81ff).But Heijenoort gives Frege (1879) this kudos: Frege’s is "perhaps the most importantsingle work ever written in logic. ... in which we see a " formula language, that is alingua characterica, a language written with special symbols, "for pure thought", that is,free from rhetorical embellishments ... constructed from specific symbols that aremanipulated according to definite rules"(van Heijenoort:1). The work of Frege wasfurther simplified and amplified by Alfred North Whitehead and Bertrand Russell in theirPrincipia Mathematica (1910–1913).The paradoxes: At the same time a number of disturbing paradoxes appeared in theliterature, in particular the Burali-Forti paradox (1897), the Russell paradox (1902–03),and the Richard Paradox (1905, Dixon 1906), (cf Kleene 1952:36–40). The resultantconsiderations led to Kurt Gödel’s paper (1931) — he specifically cites the paradox ofthe liar — that completely reduces rules of recursion to numbers.Effective calculability: In an effort to solve the Entscheidungsproblem defined preciselyby Hilbert in 1928, mathematicians first set about to define what was meant by an"effective method" or "effective calculation" or "effective calculability" (i.e., acalculation that would succeed). In rapid succession the following appeared: AlonzoChurch, Stephen Kleene and J.B. Rossers λ-calculus (cf footnote in Alonzo Church1936a:90, 1936b:110), a finely-honed definition of "general recursion" from the work ofGödel acting on suggestions of Jacques Herbrand (cf Gödels Princeton lectures of 1934)and subsequent simplifications by Kleene (1935-6:237ff, 1943:255ff), Churchs proof
  24. 24. (Church 1936:88ff) that the Entscheidungsproblem was unsolvable, Emil Posts definitionof effective calculability as a worker mindlessly following a list of instructions to moveleft or right through a sequence of rooms and while there either mark or erase a paper orobserve the paper and make a yes-no decision about the next instruction (cf his"Formulation I" 1936:289-290), Alan Turings proof of that the Entscheidungsproblemwas unsolvable by use of his "a- [automatic-] machine" (Turing 1936-7:116ff) -- in effectalmost identical to Posts "formulation", J. Barkley Rossers definition of "effectivemethod" in terms of "a machine" (Rosser 1939:226), S. C. Kleenes proposal of aprecursor to "Church thesis" that he called "Thesis I" (Kleene 1943:273–274)), and a fewyears later Kleenes renaming his Thesis "Churchs Thesis" (Kleene 1952:300, 317) andproposing "Turings Thesis" (Kleene 1952:376).[edit] Emil Post (1936) and Alan Turing (1936-7, 1939)Here is a remarkable coincidence of two men not knowing each other but describing aprocess of men-as-computers working on computations — and they yield virtuallyidentical definitions.Emil Post (1936) described the actions of a "computer" (human being) as follows:"...two concepts are involved: that of a symbol space in which the work leadingfrom problem to answer is to be carried out, and a fixed unalterable set ofdirections.His symbol space would be"a two way infinite sequence of spaces or boxes... The problem solver or workeris to move and work in this symbol space, being capable of being in, andoperating in but one box at a time.... a box is to admit of but two possibleconditions, i.e., being empty or unmarked, and having a single mark in it, say avertical stroke."One box is to be singled out and called the starting point. ...a specific problem isto be given in symbolic form by a finite number of boxes [i.e., INPUT] beingmarked with a stroke. Likewise the answer [i.e., OUTPUT] is to be given insymbolic form by such a configuration of marked boxes...."A set of directions applicable to a general problem sets up a deterministicprocess when applied to each specific problem. This process will terminate onlywhen it comes to the direction of type (C ) [i.e., STOP]." (U p. 289–290) Seemore at Post-Turing machineAlan Turing’s work (1936–1937, 1939:160) preceded that of Stibitz (1937); it isunknown if Stibitz knew of the work of Turing. Turing’s biographer believed thatTuring’s use of a typewriter-like model derived from a youthful interest: “Alan haddreamt of inventing typewriters as a boy; Mrs. Turing had a typewriter; and he could wellhave begun by asking himself what was meant by calling a typewriter mechanical"
  25. 25. (Hodges, p. 96) Given the prevalence of Morse code and telegraphy, ticker tapemachines, and Teletypes we might conjecture that all were influences.Turing — his model of computation is now called a Turing machine — begins, as didPost, with an analysis of a human computer that he whittles down to a simple set of basicmotions and "states of mind". But he continues a step further and creates a machine as amodel of computation of numbers (Turing 1936-7:116):"Computing is normally done by writing certain symbols on paper. We maysuppose this paper is divided into squares like a childs arithmetic book....I assumethen that the computation is carried out on one-dimensional paper, i.e., on a tapedivided into squares. I shall also suppose that the number of symbols which maybe printed is finite...."The behavior of the computer at any moment is determined by the symbolswhich he is observing, and his "state of mind" at that moment. We may supposethat there is a bound B to the number of symbols or squares which the computercan observe at one moment. If he wishes to observe more, he must use successiveobservations. We will also suppose that the number of states of mind which needbe taken into account is finite..."Let us imagine that the operations performed by the computer to be split up intosimple operations which are so elementary that it is not easy to imagine themfurther divided" (Turing 1936-7:136).Turings reduction yields the following:"The simple operations must therefore include:"(a) Changes of the symbol on one of the observed squares"(b) Changes of one of the squares observed to another square within L squares ofone of the previously observed squares."It may be that some of these change necessarily invoke a change of state of mind. Themost general single operation must therefore be taken to be one of the following:"(A) A possible change (a) of symbol together with a possible change of state ofmind."(B) A possible change (b) of observed squares, together with a possible changeof state of mind""We may now construct a machine to do the work of this computer."((Turing1936-7:136).A few years later, Turing expanded his analysis (thesis, definition) with this forcefulexpression of it:"A function is said to be "effectivey calculable" if its values can be found by somepurely mechanical process. Although it is fairly easy to get an intuitive grasp ofthis idea, it is neverthessless desirable to have some more definite, mathematical
  26. 26. expressible definition . . . [he discusses the history of the definition pretty much aspresented above with respect to Gödel, Herbrand, Kleene, Church, Turing andPost] . . . We may take this statement literally, understanding by a purelymechanical process one which could be carried out by a machine. It is possible togive a mathematical description, in a certain normal form, of the structures ofthese machines. The development of these ideas leads to the authors definition ofa computable function, and to an identification of computability † with effectivecalculability . . . ."† We shall use the expression "computable function" to mean a functioncalculable by a machine, and we let "effectively calculabile" refer to the intuitiveidea without particular identification with any one of these definitions." (Turing1939:160).[edit] J. B. Rosser (1939) and S. C. Kleene (1943)J. Barkley Rosser boldly defined an ‘effective [mathematical] method’ in the followingmanner (boldface added):"Effective method is used here in the rather special sense of a method each stepof which is precisely determined and which is certain to produce the answer in afinite number of steps. With this special meaning, three different precisedefinitions have been given to date. [his footnote #5; see discussion immediatelybelow]. The simplest of these to state (due to Post and Turing) says essentiallythat an effective method of solving certain sets of problems exists if one canbuild a machine which will then solve any problem of the set with no humanintervention beyond inserting the question and (later) reading the answer.All three definitions are equivalent, so it doesnt matter which one is used.Moreover, the fact that all three are equivalent is a very strong argument for thecorrectness of any one." (Rosser 1939:225–6)Rossers footnote #5 references the work of (1) Church and Kleene and their definition ofλ-definability, in particular Churchs use of it in his An Unsolvable Problem ofElementary Number Theory (1936); (2) Herbrand and Gödel and their use of recursion inparticular Gödels use in his famous paper On Formally Undecidable Propositions ofPrincipia Mathematica and Related Systems I (1931); and (3) Post (1936) and Turing(1936-7) in their mechanism-models of computation.Stephen C. Kleene defined as his now-famous "Thesis I" known as "the Church-TuringThesis". But he did this in the following context (boldface in original):"12. Algorithmic theories... In setting up a complete algorithmic theory, what wedo is to describe a procedure, performable for each set of values of theindependent variables, which procedure necessarily terminates and in suchmanner that from the outcome we can read a definite answer, "yes" or "no," to thequestion, "is the predicate value true?”" (Kleene 1943:273)
  27. 27. [edit] History after 1950A number of efforts have been directed toward further refinement of the definition of"algorithm", and activity is on-going because of issues surrounding, in particular,foundations of mathematics (especially the Church-Turing Thesis) and philosophy ofmind (especially arguments around artificial intelligence). For more, see Algorithmcharacterizations.Pseudocode (derived from pseudo and code) is a compact and informal high-leveldescription of a computer programming algorithm that uses the structural conventions ofprogramming languages, but omits detailed subroutines, variable declarations, andlanguage-specific syntax. The programming language is augmented with natural languagedescriptions of the details, where convenient, or with compact mathematical notation.The purpose of using pseudocode as opposed the language syntax is that it is easier forhumans to read. This is often achieved by making the sample application-independent somore specific items (i/o variables, etc.) can be added later.Pseudocode resembles, but should not be confused with, skeleton programs includingdummy code, which can be compiled without errors. Flowcharts can be thought of as agraphical form of pseudocode.Contents[hide]• 1 Syntax• 2 Application• 3 Examples of pseudocode• 4 Mathematical style pseudocode• 5 Machine compilation or interpretationo 5.1 Natural language grammar in programming languageso 5.2 Mathematical programming languages• 6 See also• 7 External links[edit] SyntaxAs the name suggests, pseudocode generally does not actually obey the syntax rules ofany particular language; there is no systematic standard form, although any particularwriter will generally borrow the appearance of a particular language. Popular sourcesinclude PASCAL, C, Java, BASIC, Lisp, and ALGOL. Details not relevant to thealgorithm (such as memory management code) are usually omitted. Blocks of code, for
  28. 28. example code contained within a loop, may be described in a one-line natural languagesentence.Depending on the writer, pseudocode may therefore vary widely in style, from a near-exact imitation of a real programming language at one extreme, to a descriptionapproaching formatted prose at the other.[edit] ApplicationTextbooks and scientific publications related to computer science and numericalcomputation often use pseudocode in description of algorithms, so that all programmerscan understand them, even if they do not all know the same programming languages. Intextbooks, there is usually an accompanying introduction explaining the particularconventions in use. The level of detail of such languages may in some cases approachthat of formalized general-purpose languages — for example, Knuths seminal textbookThe Art of Computer Programming describes algorithms in a fully-specified assemblylanguage for a non-existent microprocessor.A programmer who needs to implement a specific algorithm, especially an unfamiliarone, will often start with a pseudocode description, and then simply "translate" thatdescription into the target programming language and modify it to interact correctly withthe rest of the program. Programmers may also start a project by sketching out the codein pseudocode on paper before writing it in its actual language, as a top-down structuringapproach.[edit] Examples of pseudocodeAn example of how pseudocode differs from regular code is below.Regular code (written in PHP):<?phpif (is_valid($cc_number)) {execute_transaction($cc_number,$order);} else {show_failure();}?>Pseudocode:if credit card number is validexecute transaction based onnumber and orderelseshow a generic failuremessageend ifThe pseudocode of the Hello world program is particularly simple:output Hello World[edit] Mathematical style pseudocode
  29. 29. In numerical computation, pseudocode often consists of mathematical notation, typicallyfrom set and matrix theory, mixed with the control structures of a conventionalprogramming language, and perhaps also natural language descriptions. This is a compactand often informal notation that can be understood by a wide range of mathematicallytrained people, and is frequently used as a way to describe mathematical algorithms.Normally non-ASCII typesetting is used for the mathematical equations, for example bymeans of TeX or MathML markup, or proprietary formula editors.Mathematical style pseudocode is sometimes referred to as pidgin code, for examplepidgin ALGOL (the origin of the concept), pidgin Fortran, pidgin BASIC, pidgin Pascal,and pidgin C.[edit] Machine compilation or interpretationIt is often suggested that future programming languages will be more similar topseudocode or natural language than to present-day languages; the idea is that increasingcomputer speeds and advances in compiler technology will permit computers to createprograms from descriptions of algorithms, instead of requiring the details to beimplemented by a human.[edit] Natural language grammar in programming languagesVarious attempts to bring elements of natural language grammar into computerprogramming have produced programming languages such as HyperTalk, Lingo,AppleScript, SQL and Inform. In these languages, parentheses and other specialcharacters are replaced by prepositions, resulting in quite talkative code. This may makeit easier for a person without knowledge about the language to understand the code andperhaps also to learn the language. However, the similarity to natural language is usuallymore cosmetic than genuine. The syntax rules are just as strict and formal as inconventional programming, and do not necessarily make development of the programseasier.[edit] Mathematical programming languagesAn alternative to using mathematical pseudocode (involving set theory notation or matrixoperations) for documentation of algorithms is to use a formal mathematicalprogramming language that is a mix of non-ASCII mathematical notation and programcontrol structures. Then the code can be parsed and interpreted by a machine.Several formal specification languages include set theory notation using specialcharacters. Examples are:• Z notation• Vienna Development Method Specification Language (VDM-SL).
  30. 30. Some array programming languages include vectorized expressions and matrixoperations as non-ASCII formulas, mixed with conventional control structures. Examplesare:• A programming language (APL), and its dialects APLX and A+.• MathCAD.The process of converting a problem to computer code is a five-step one and you mayhave to repeat some steps in response to difficulties.Step 1: Define the problem. Before starting, its important you completely understand theproblems nature any assumptions.Step 2: Plan the solution. Break the problems solution down into its smallest steps anddetermine how they are logically linked.Step 3: Code the program. Translate the logical solution into a programming languagethe computer understands.Step 4: Test the program. Check the program logic by hand and then by machine usingvarious test cases.
  31. 31. Step 5: Document everything. The most important step in many cases. You wont alwaysremember what you did or be able to figure it out.TranslatorsTo get from your programming language down to the binary steps the computerunderstands requires some form of translator. Translators come in two general types:• Compiler: Translates an entire program at one time then executes.o Compiled programs execute much faster.o Compilation is usually a multi-step process.o Compilers do not require space in memory when programs run.• Interpreter: Translates a program line at a time while executing.o Interpreted programs are slower because translation takes times.o Interpretation translates in one step.o Interpreters must be in memory while a program is running.Programming Language HierarchyThere are a variety of programming languages, falling into several classes. These classesrange from actual machine code through languages with very English-like structure.There are other trade-offs as shown here.Language English-like Ease of Use EfficiencyMachine Not Very Hard VeryAssemblyHigh-levelNonprocedural Very Easy Not VeryThe basic trade-off you have to make is between ease of use and efficiency. Becausehigher level languages tend to require lots of extra code, they dont use the machine asefficiently as possible. This partially accounts for the need for more powerful hardware torun newer software.Comp 150 - Algorithms & Pseudo-Code(revised 01/11/2008)
  32. 32. Definition of Algorithm (after Al Kho-war-iz-mi a 9th century Persian mathematician) -an ordered sequence of unambiguous and well-defined instructions that performs sometask and halts in finite timeLets examine the four parts of this definition more closely1. an ordered sequence means that you can number the steps (its socks then shoes!)2. unambiguous and well-defined instructions means that each instruction is clear,do-able, and can be done without difficulty3. performs some task4. halts in finite time (algorithms terminate!)Algorithms can be executed by a computing agent which is not necessarily a computer.Three Catagories of Algorithmic OperationsAlgorithmic operations are ordered in that there is a first instruction, a second instructionetc. However, this is not enough. An algorithm must have the ability to alter the order ofits instructions. An instruction that alters the order of an algorithm is called a controlstructureThree Categories of Algorithmic Operations:1. sequential operations - instructions are executed in order2. conditional ("question asking") operations - a control structure that asks atrue/false question and then selects the next instruction based on the answer3. iterative operations (loops) - a control structure that repeats the execution of ablock of instructionsUnfortunately not every problem or task has a "good" algorithmic solution. There are1. unsolvable problems - no algorithm can exist to solve the problem (HaltingProblem)2. "hard" (intractable) problems - algorithm takes too long to solve the problem(Traveling Salesman Problem)3. problems with no known algorithmic solutionHow to represent algorithms?1. Use natural languageso too verboseo too "context-sensitive"- relies on experience of reader2. Use formal programming languageso too low level
  33. 33. o requires us to deal with complicated syntax of programming language3. Pseudo-Code - natural language constructs modeled to look like statementsavailable in many programming languagesPseudo-Code is simply a numbered list of instructions to perform some task. In thiscourse we will enforce three standards for good pseudo code1. Number each instruction. This is to enforce the notion of an ordered sequenceof ... operations. Furthermore we introduce a dot notation (e.g. 3.1 come after 3but before 4) to number subordinate operations for conditional and iterativeoperations2. Each instruction should be unambiguous (that is the computing agent, in this casethe reader, is capable of carrying out the instruction) and effectively computable(do-able).3. Completeness. Nothing is left out.Pseudo-code is best understood by looking at examples. Each example belowdemonstrates one of the control structures used in algorithms : sequential operations,conditional operations, and iterative operations. We also list all variables used at the endof the pseudo-code.Example #1 - Computing Sales Tax : Pseudo-code the task of computing the final priceof an item after figuring in sales tax. Note the three types of instructions: input (get),process/calculate (=) and output (display)1. get price of item2. get sales tax rate3. sales tax = price of time times sales tax rate4 final prince = price of item plus sales tax5. display final price6. haltVariables: price of item, sales tax rate, sales tax, final priceNote that the operations are numbered and each operation is unambiguous and effectivelycomputable. We also extract and list all variables used in our pseudo-code. This will beuseful when translating pseudo-code into a programming languageExample #2 - Computing Weekly Wages: Gross pay depends on the pay rate and thenumber of hours worked per week. However, if you work more than 40 hours, you getpaid time-and-a-half for all hours worked over 40. Pseudo-code the task of computinggross pay given pay rate and hours worked.1. get hours worked
  34. 34. 2. get pay rate3. if hours worked ≤ 40 then3.1 gross pay = pay rate times hours worked4. else4.1 gross pay = pay rate times 40 plus 1.5 times pay rate times(hours worked minus 40)5. display gross pay6. haltvariables: hours worked, ray rate, gross payThis example introduces the conditional control structure. On the basis of the true/falsequestion asked in line 3, we execute line 3.1 if the answer is True; otherwise if the answeris False we execute the lines subordinate to line 4 (i.e. line 4.1). In both cases we resumethe pseudo-code at line 5.Example #3 - Computing a Quiz Average: Pseudo-code a routine to calculate your quizaverage.1. get number of quizzes2. sum = 03. count = 04. while count < number of quizzes4.1 get quiz grade4.2 sum = sum + quiz grade4.3 count = count + 15. average = sum / number of quizzes6. display average7. haltvariables: number of quizzes, sum ,count, quiz grade, averageThis example introduces an iterative control statement. As long as the condition in line 4is True, we execute the subordinate operations 4.1 - 4.3. When the condition becomesFalse, we resume the pseudo-code at line 5.This is an example of a top-test or while do iterative control structure. There is also abottom-test or repeat until iterative control structure which executes a block of statementsuntil the condition tested at the end of the block is False.Pseudo-code is one important step in the process of writing a program.Pseudo-code Language Constructions : A Summary
  35. 35. Computation/Assignmentset the value of "variable" to :"arithmetic expression" or"variable" equals "expression" or"variable" = "expression"Input/Outputget "variable", "variable", ...display "variable", "variable", ...Conditional (dot notation used for numbering subordinate statements)6. if "condition"6.1 (subordinate) statement 16.2 etc ...7. else7.1 (subordinate) statement 27.2 etc ...Iterative (dot notation used for numbering subordinate statements)9. while "condition"9.1 (subordinate) statement 19.2 etc ...Return to Comp 150 Home PageDetermining the Day of the Week from the Date(see Asgt 06 - Calculating Day of the Week)03/17/2004The day of the week for any date can be obtained from the following two data items :A. The ordinal position of the day within the year (e.g. March 25, 1999 was day 84).Well call this the year_ordinal.B. The ordinal position of the day within the week for January 1 of that year (whereSunday is 1, Monday is 2 etc.). The ordinal position of the day within the week well callthe week_ordinal and week_ordinal for January 1 well refer call week_ordinal(1/1). Thisvalue depends on the year.
  36. 36. Given these two numbers, year_ordinal (the ordinal position of day within the year) andweek_ordinal(1/1) (the ordinal position of January 1 within the week), the week_ordinalfor any date is easily found by the formula((year_ordinal - 1) + (week_ordinal(1/1) - 1) ) modulo 7 + 1Essentially you start at the ordinal position of January 1 with in the week and increment itby the ordinal position of the day within the year minus 1 (modulo 7) then add 1 to obtainordinal position of the day within the week.For example, if the January 1 of the year was a Wednesday (day of week 4) and youwanted to find the day of the week January 12 fell on (day number 12) then starting at 3you count forward 11 units (modulo 7)3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0You end up at 0. Adding 1 to 0 yields 1 so January 12 is a Sunday. You can check thatthis works using the calender below by starting at Wednesday the 1st and countingforward 11 days to arrive at Sunday!Su M Tu W Th F Sa1 2 3 45 6 7 8 9 10 1112 13 14 15 16 17 1819 20 21 22 23 24 2526 27 28 29 30 31Calculating Year Ordinal: the ordinal postion of the day within the yearCalculating the year_ordinal is easily done if we make use of the following table whichlists the number of days before the 1st of each monthMonth Number of Daysbefore 1stJan 0Feb 31Mar 59*Apr 90*May 120*Jun 151*Jul 181*Aug 212*Sept 243*Oct 273*Nov 304*Dec 334* Note : * indicates add 1 for leapyearsThis table is obtained by summing the days of all prior months.
  37. 37. The year ordinal for any date is obtained by adding the proper value for that month fromthe table to the day.ExampleJune 15, 2003 is day 166 (151 + 15).Calculating Week_Ordinal (1/1): the ordinal position of January 1Since 365 is not divisible by 7 but 365 equals 52 times 7 plus 1, the ordinal position ofthe day within the week for January 1 advances by 1 day from one year to the next exceptwhen the previous year was a leap year in which case it advances by 2 days.ExampleSince January 1, 1998 fell on a Thursday, January 1, 1999 fell on a Friday since thereare 365 days between them.Since January 1, 2000 fell on a Saturday, January 1, 2001 will fall on a Monday sincethere are 366 days between them.Given that the January 1 advances one day except when going from a leap year in whichcase it advances two days, its not difficult to show that there is a 28 year cycle fordetermining the day for January 1. Consider the years 1901 through 1928. The cyclestarts with Tuesday, January 1 1901. Years in red indicate where the ordinal positionadvances by 21901 - Tu 1902 - W 1903 - Th 1904 - F1905 - Su 1906 - M 1907 - Tu 1908 - W1909 - F 1910 - Sa 1911 - Su 1912 - M1913 - W 1914 - Th 1915 - F 1916 - Sa1917 - M 1918 - Tu 1919 - W 1920 - Th1921 - Sa 1922 - Su 1923 - M 1924 - Tu1925 - Th 1926 - F 1927 - Sa 1928 - Su1929 - Tu 1930 - W 1931 - Th 1932 - FAs is shown, the pattern repeats with 1929. The cycle is 28 years long.Since the cycle repeats every 28 years, if we calculate the difference between the currentyear and 1901 modulo 28, we will know where we are within the 28 year cycle. Using theformula we obtaina = (year - 1901) modulo 28where a is in integer between 0 and 27.
  38. 38. Example : For the year 2000,(2000 - 1901) modulo 28 equals 15.and if you count 15 forward from 1901 - Tu (1902 - W is 1, 1903 - Th is 2 etc) you endup at 1916 - Sa. So January 1, 2000 was a Saturday.There is a trick we can used to calculate the day instead counting forward on the 1901 -1928 table. Given any year, the value of a that we calculate is the offset into the 28 yearcycle. And if we did not have to take into account the effect of leap years, if we added ato the to the first day value for 1901 modulo 7, we would have the first day for the year;that is calculate (3 + a) mod 7.However this does not take into account the effect of leap years which pushed January 1ahead two days instead of 1. So if we add the number of leap years in the cycle, b whereb = floor (a / 4)the sum of a plus b modulo 7 tells us how many days we have to advance January 1 fromTuesday. Since modulo 7 returns a value between 0 and 6 and we normally number thedays of the week 1 (Sunday) through 7 (Saturday), we have to add 1.week_ordinal(1/1) = (2 + a + b) modulo 7 + 1Thus the week_ordinal(1/1) can be found by the three formulas1. a = (year - 1901) mod 282. b = floor(a/4)3. week_ordinal(1/1) = (2 + a + b) modulo 7 + 1SummaryTo find the ordinal position of the day within the week for any date between Jan 1, 1901and Dec 31 20991. Find the year_ordinal using the table of days before the first of the month2. Calculate week_ordinal(1/1) as followsa = (year - 1901) modulo 28b = floor (a/4)week_ordinal(1/1) = (2 + a + b) modulo 7 + 13. Day of the Week = ((year_ordinal - 1) + (week_ordinal(1/1) - 1)) modulo 7 + 1
  39. 39. Addendum1. This algorithm only works for the dates between 1901 and 2100. The fact that 2100is not a leap year prohibits the 28 year cycle for obtaining the first day from carryingover into the 22nd century.2. The algorithm presented makes use of modular arithmetic with its use of modulo 28and modulo 7 calculations. In modular arithmetic its easier to starting counting at 0instead of 1. Consequently the algorithm could be simplified if we made the followingchangesa. Number the days from 0 to 6 with Sunday being day 0 and Saturday being day 6b. Number the days of the year from 0 to 364 (or 365 for leap year) with January 1being day 0 etc.Alternate AlgorithmNumber the days of the week 0 - 6 and the days of the year 0 - 364 (or 365 for leap year)1. Find the year_ordinal using the table of days before the first of the month exceptsubtract 1 from this value. This would number the day of the year from 0 to 364 (or 365for leap years)2. Calculate week_ordinal(1/1) as followsa = (year - 1901) modulo 28b = floor (a/4)week_ordinal(1/1) = (2 + a + b) modulo 7We note that Tuesday January 1, 1901 is now day 2 under the new numbering (Sunday isday 0)3. Day of the Week = (year_ordinal + week_ordinal(1/1)) modulo 7Example : Find the Day of the Year for March 21, 20041. March 21, 2000 is day 60 + 21 - 1 = 802. a = (2004 - 1901) modulo 28 = 19b = floor (19/4) = 4week_ordinal(1/1) = (2 + 19 + 4) modulo 7 = 4 (Thursday)3. week_ordinal(3/21/2004) = (80+4) modulo 7 = 0 (Sunday)
  40. 40. Pseudocode ExamplesModified 15 December 1999An algorithm is a procedure for solving a problem in terms of the actionsto be executed and the order in which those actions are to beexecuted. An algorithm is merely the sequence of steps taken to solvea problem. The steps are normally "sequence," "selection, ""iteration," and a case-type statement.In C, "sequence statements" are imperatives. The "selection" is the "ifthen else" statement, and the iteration is satisfied by a number ofstatements, such as the "while," " do," and the "for," while the case-typestatement is satisfied by the "switch" statement.Pseudocode is an artificial and informal language that helps programmersdevelop algorithms. Pseudocode is a "text-based" detail (algorithmic)design tool.The rules of Pseudocode are reasonably straightforward. All statementsshowing "dependency" are to be indented. These include while, do, for, if,switch. Examples below will illustrate this notion.GUIDE TO PSEUDOCODE LEVEL OF DETAIL: Given record/filedescriptions, pseudocode should be created in sufficient detail so as todirectly support the programming effort. It is the purpose of pseudocodeto elaborate on the algorithmic detail and not just cite an abstraction.Examples:1.If students grade is greater than or equal to 60Print "passed"elsePrint "failed"endif2.
  41. 41. Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalendwhileSet the class average to the total divided by tenPrint the class average.3.Initialize total to zeroInitialize counter to zeroInput the first gradewhile the user has not as yet entered the sentineladd this grade into the running totaladd one to the grade counterinput the next grade (possibly the sentinel)endwhileif the counter is not equal to zeroset the average to the total divided by the counterprint the averageelseprint no grades were enteredendif4.initialize passes to zeroinitialize failures to zeroinitialize student to onewhile student counter is less than or equal to teninput the next exam resultif the student passedadd one to passeselseadd one to failuresadd one to student counterendifendwhileprint the number of passes
  42. 42. print the number of failuresif eight or more students passedprint "raise tuition"endif5.Larger example:NOTE: NEVER ANY DATA DECLARATIONS IN PSEUDOCODEPrint out appropriate heading and make it prettyWhile not EOF do:Scan over blanks and white space until a char is found(get first character on the line)set cant-be-ascending-flag to 0set consec cntr to 1set ascending cntr to 1putchar first char of string to screenset read character to hold characterWhile next character read != blanks and white spaceputchar out on screenif new char = hold char + 1add 1 to consec cntrset hold char = new charcontinueendifif new char >= hold charif consec cntr < 3set consec cntr to 1endifset hold char = new charcontinueendifif new char < hold charif consec cntr < 3set consec cntr to 1endifset hold char = new charset cant be ascending flag to 1continueendifend whileif consec cntr >= 3printf (Appropriate message 1 and skip a line)add 1 to consec totalendifif cant be ascending flag = 0printf (Appropriate message 2 and skip a line)add 1 to ascending totalelseprintf (Sorry message and skip a line)add 1 to sorry total
  43. 43. endifend WhilePrint out totals: Number of consecs, ascendings, and sorries.StopSome Keywords that should be Used and Additional PointsFor looping and selection, The keywords that are to be used include DoWhile...EndDo; Do Until...Enddo; While .... Endwhile is acceptable.Also, Loop .... endloop is also VERY good and is languageindependent. Case...EndCase; If...Endif; Call ... with (parameters);Call; Return ....; Return; When;Always use scope terminators for loops and iteration.As verbs, use the words Generate, Compute, Process, etc. Words such asset, reset, increment, compute, calculate, add, sum, multiply, ... print,display, input, output, edit, test , etc. with careful indentation tend to fosterdesirable pseudocode. Also, using words such as Set and Initialize, whenassigning values to variables is also desirable.More on Formatting and Conventions in Pseudocoding INDENTATION in pseudocode should be identical to itsimplementation in a programming language. Try to indent at leastfour spaces. As noted above, the pseudocode entries are to be cryptic, ANDSHOULD NOT BE PROSE. NO SENTENCES. No flower boxes (discussed ahead) in your pseudocode. Do not include data declarations in your pseudocode. But do cite variables that are initialized as part of their declarations.E.g. "initialize count to zero" is a good entry.Function Calls, Function Documentation, and Pseudocode Calls to Functions should appear as:Call FunctionName (arguments: field1, field2, etc.) Returns in functions should appear as:
  44. 44. Return (field1) Function headers should appear as:FunctionName (parameters: field1, field2, etc. ) Note that in C, arguments and parameters such as "fieldn" could bewritten: "pointer to fieldn ...." Functions called with addresses should be written as:Call FunctionName (arguments: pointer to fieldn, pointer to field1,etc.) Function headers containing pointers should be indicated as:FunctionName (parameters: pointer to field1, pointer to field2, ...) Returns in functions where a pointer is returned:Return (pointer to fieldn) It would not hurt the appearance of your pseudocode to draw a line ormake your function header line "bold" in your pseudocode. Try toset off your functions. Try to use scope terminators in your pseudocode and source code too. Itreally hels the readability of the text.Source Code EVERY function should have a flowerbox PRECEDING IT. Thisflower box is to include the functions name, the main purpose of thefunction, parameters it is expecting (number and type), and the typeof the data it returns. All of these listed items are to be on separatelines with spaces in between each explanatory item. FORMAT of flowerbox should be********************************************************Function: ( cryptic text describing single function....... (indented like this).......Calls: Start listing functions "this" function callsShow these functions: one per line, indentedCalled by: List of functions that calls "this" functionShow these functions: one per line, indented.Input Parameters: list, if appropriate; else NoneReturns: List, if appropriate.**************************************************************** INDENTATION is critically important in Source Code. Followstandard examples given in class. If in doubt, ASK. Always indentstatements within IFs, FOR loops, WILLE loops, SWITCH
  45. 45. statements, etc. a consistent number of spaces, such as four.Alternatively, use the tab key. One or two spaces is insufficient. Use scope terminators at the end of if statements, for statements, whilestatements, and at the end of functions. It will make your programmuch more readable.SPELLING ERRORS ARE NOT ACCEPTABLEPSEUDOCODE STANDARDPseudocode is a kind of structured english for describing algorithms. It allows thedesigner to focus on the logic of the algorithm without being distracted by details oflanguage syntax. At the same time, the pseudocode needs to be complete. It describe theentire logic of the algorithm so that implementation becomes a rote mechanical task oftranslating line by line into source code.In general the vocabulary used in the pseudocode should be the vocabulary of theproblem domain, not of the implementation domain. The pseudocode is a narrative forsomeone who knows the requirements (problem domain) and is trying to learn how thesolution is organized. E.g.,Extract the next word from the line (good)set word to get next token (poor)Append the file extension to the name (good)name = name + extension (poor)FOR all the characters in the name (good)FOR character = first to last (ok)Note that the logic must be decomposed to the level of a single loop or decision. Thus"Search the list and find the customer with highest balance" is too vague because it takesa loop AND a nested decision to implement it. Its okay to use "Find" or "Lookup" iftheres a predefined function for it such as String.indexOf().Each textbook and each individual designer may have their own personal style ofpseudocode. Pseudocode is not a rigorous notation, since it is read by other people, not bythe computer. There is no universal "standard" for the industry, but for instructionalpurposes it is helpful if we all follow a similar style. The format below is recommendedfor expressing your solutions in our class.